package net.ecpt.crm.services;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.DelegatorFactory;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.wvtools.utils.CommonUtils;
import org.ofbiz.wvtools.utils.WvDatetimeUtils;

import javolution.util.FastList;
import javolution.util.FastMap;

public class CrmReportServices {
    public static final String module = CrmReportServices.class.getName();

    private static boolean isNumeric(String str) {
	Pattern pattern = Pattern.compile("[0-9]*");
	return pattern.matcher(str).matches();
    }

    public static Map<String, Object> ecaCustomerAndBusiness(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();

	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	Timestamp fromDate_chengmo = WvDatetimeUtils.getLastDay(thruDate, new Long(-90));
	try {
	    List<GenericValue> entityList = FastList.newInstance();
	    // 活跃客户 客户如果有成功入仓商机，就始终是活跃的客户。 不随着顶端的时间筛选而变。
	    List<EntityCondition> mainCond_active_customer = new ArrayList();

	    mainCond_active_customer
		    .add(EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN, fromDate_chengmo));
	    mainCond_active_customer.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    List<GenericValue> activeCustomerList = delegator.findList("CrmCustomer",
		    EntityCondition.makeCondition(mainCond_active_customer, EntityOperator.AND), null,
		    UtilMisc.toList("-createdStamp"), null, false);

	    for (GenericValue item : activeCustomerList) {
		String infoStatusId = item.getString("infoStatusId");
		if (!"2".equals(infoStatusId) && !"4".equals(infoStatusId) && !"6".equals(infoStatusId)) {
		    item.set("infoStatusId", "3");
		    entityList.add(item);
		}
	    }

	    // 沉默客户 不随着顶端的时间筛选而变。
	    // 1.1、客户名下无商机，且最近三个月内客户数据无更新；
	    // 1.2、客户名下有商机，客户数据最近三个月内无更新，且最近三个月内该客户名下所有的（非入仓状态的/非失败状态的）商机无更新；
	    List<EntityCondition> mainCond_six_month_customer = new ArrayList();

	    mainCond_six_month_customer
		    .add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN, fromDate_chengmo));
	    mainCond_six_month_customer.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    List<GenericValue> sixMonthCrmCustomerList = delegator.findList("CrmCustomer",
		    EntityCondition.makeCondition(mainCond_six_month_customer, EntityOperator.AND), null,
		    UtilMisc.toList("-createdStamp"), null, false);

	    for (GenericValue item : sixMonthCrmCustomerList) {
		String infoStatusId = item.getString("infoStatusId");
		if (!"2".equals(infoStatusId) && !"4".equals(infoStatusId) && !"6".equals(infoStatusId)) {
		    item.set("infoStatusId", "1");
		    entityList.add(item);
		}

	    }

	    // 活跃商机 （DB逻辑：3个月内有更新的（0~5状态）商机）； 活跃商机为0~5，包含5
	    // //成功商机为6 失败商机是7 //总商机数-沉默商机-入仓商机-失败商机
	    List<EntityCondition> mainCond_active_business = new ArrayList();
	    mainCond_active_business
		    .add(EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN, fromDate_chengmo));
	    mainCond_active_business.add(EntityCondition.makeCondition("statusId", EntityOperator.IN,
		    UtilMisc.toList("0", "1", "2", "3", "4")));

	    mainCond_active_business.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    List<GenericValue> activeBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond_active_business, EntityOperator.AND), null,
		    UtilMisc.toList("-createdStamp"), null, false);

	    for (GenericValue item : activeBusinessList) {
		String infoStatusId = item.getString("infoStatusId");
		if (!"2".equals(infoStatusId) && !"4".equals(infoStatusId) && !"6".equals(infoStatusId)) {
		    item.set("infoStatusId", "3");
		    entityList.add(item);
		}
	    }

	    // 沉默商机 最近三个月（非入仓状态的/非失败状态的）商机无更新； 沉默商机包含5和7状态
	    List<EntityCondition> mainCond_chengmo = new ArrayList();
	    mainCond_chengmo
		    .add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN, fromDate_chengmo));
	    mainCond_chengmo.add(EntityCondition.makeCondition("statusId", EntityOperator.IN,
		    UtilMisc.toList("0", "1", "2", "3", "4", "7")));

	    mainCond_chengmo.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    List<GenericValue> sixMonthCrmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond_chengmo, EntityOperator.AND), null,
		    UtilMisc.toList("-createdStamp"), null, false);

	    for (GenericValue item : sixMonthCrmBusinessList) {
		String infoStatusId = item.getString("infoStatusId");
		if (!"2".equals(infoStatusId) && !"4".equals(infoStatusId) && !"6".equals(infoStatusId)) {
		    item.set("infoStatusId", "1");
		    entityList.add(item);
		}
	    }
	    // 成功商机
	    List<EntityCondition> mainCond_success = new ArrayList();
	    mainCond_success.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "5"));
	    mainCond_success.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    List<GenericValue> successCrmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond_success, EntityOperator.AND), null,
		    UtilMisc.toList("-createdStamp"), null, false);
	    for (GenericValue item : successCrmBusinessList) {
		item.set("infoStatusId", "5");
		entityList.add(item);
	    }
	    delegator.storeAll(entityList);

	    List<GenericValue> list2 = FastList.newInstance();
	    for (GenericValue item : successCrmBusinessList) {
		// 活跃客户2
		if (UtilValidate.isEmpty(item.get("customerId"))) {
		    continue;
		}
		String customerId = item.getString("customerId");
		GenericValue cust = delegator.findOne("CrmCustomer", false, UtilMisc.toMap("id", customerId));
		if (UtilValidate.isEmpty(cust)) {
		    continue;
		}
		String infoStatusId = "";
		if (UtilValidate.isNotEmpty(cust.get("infoStatusId"))) {
		    infoStatusId = cust.getString("infoStatusId");
		}

		if (!"4".equals(infoStatusId) && !"6".equals(infoStatusId)) {
		    cust.set("infoStatusId", "3");
		    list2.add(cust);
		}

	    }
	    delegator.storeAll(list2);
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	    return ServiceUtil.returnError(e.getMessage());
	}
	return result;
    }

    /**
     * 仪表盘数据
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map<String, Object> getCrmDashBoardDataNum(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");

	String ownerUserId = userLogin.getString("userLoginId");
	String personTypeId = (String) context.get("personTypeId");// 本人 ，本人及下属 //全国 大区 bu等等
	String dateTypeId = (String) context.get("dateTypeId");// 本日 ，本周，本月 ，本年
	Timestamp createTime_fld0_value = (Timestamp) context.get("createTime_fld0_value");
	Timestamp createTime_fld1_value = (Timestamp) context.get("createTime_fld1_value");

	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-1));

	try {
	    List ownerUserIdList = new ArrayList();

	    List mainCondUser = new ArrayList();

	    if ("1".equals(personTypeId)) {// 本人
		ownerUserIdList.add(ownerUserId);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
	    } else if ("2".equals(personTypeId)) {// 本bu
		List<GenericValue> subordinateList = delegator.findByAnd("UserLogin",
			UtilMisc.toMap("superiorId", ownerUserId), null, true);
		for (GenericValue subordinate : subordinateList) {
		    String subordinateUserLoginId = subordinate.getString("userLoginId");
		    ownerUserIdList.add(subordinateUserLoginId);
		}
		ownerUserIdList.add(ownerUserId);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
	    } else if ("allData".equals(personTypeId)) { // 全国
		// ownerUserIdList.add(ownerUserId);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.NOT_EQUAL, "public"));
	    } else if ("3".equals(personTypeId)) { // 本大区
		// 先找到人属于那个bu.找到bu属于哪个大区.
		List<GenericValue> shipList = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdTo", ownerUserId), null, true);
		if (UtilValidate.isNotEmpty(shipList)) {
//		    // 获取buCode
		    String buCode = EntityUtil.getFirst(shipList).getString("partyIdFrom");
		    List<GenericValue> dataList1 = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("dictionaryCode", buCode), null, true);

		    GenericValue data1 = EntityUtil.getFirst(dataList1);
		    String areaId = data1.getString("parentId");
		    // 获取大区ID
		    if (UtilValidate.isNotEmpty(areaId)) {
			// 获取大区下的bu列表
			List<GenericValue> sunBuList = delegator.findByAnd("DataDictionary",
				UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT", "parentId", areaId), null, true);
			for (GenericValue bu : sunBuList) {
			    List<GenericValue> itemShipList = delegator.findByAnd("CoRelationship",
				    UtilMisc.toMap("partyIdFrom", bu.getString("dictionaryCode")), null, true);
			    for (GenericValue coRelationship : itemShipList) {
				String partyIdTo = coRelationship.getString("partyIdTo");
				ownerUserIdList.add(partyIdTo);
			    }
			}
		    }

		}
		ownerUserIdList.add(ownerUserId);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
	    } else if (isNumeric(personTypeId)) { // 人员
		ownerUserId = personTypeId;
		ownerUserIdList.add(ownerUserId);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
	    } else {
		List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryCode", personTypeId), null, true);
		GenericValue data = EntityUtil.getFirst(dataList);
		String dictionaryTypeId = data.getString("dictionaryTypeId");
		// 各大区
		if (dictionaryTypeId.equals("AREA_DEPARTMENT")) {
		    List<GenericValue> childList = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("parentId", data.getString("dictionaryId")), null, true);
		    for (GenericValue child : childList) {
			String code = child.getString("dictionaryCode");
			List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
				UtilMisc.toMap("partyIdFrom", code), null, true);
			for (GenericValue coRelationship : coRelationshipList) {
			    String partyIdTo = coRelationship.getString("partyIdTo");
			    ownerUserIdList.add(partyIdTo);
			}
		    }
		    mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));

		} else {
		    // 各bu
		    List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
			    UtilMisc.toMap("partyIdFrom", personTypeId), null, true);
		    for (GenericValue coRelationship : coRelationshipList) {
			String partyIdTo = coRelationship.getString("partyIdTo");
			ownerUserIdList.add(partyIdTo);
		    }
		    mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));

		}
	    }

	    List mainCond0 = new ArrayList();
	    mainCond0.addAll(mainCondUser);
	    if ("1".equals(dateTypeId)) {
		mainCond0.add(
			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("2".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));
		mainCond0.add(
			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));

	    } else if ("3".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-31));
		mainCond0.add(
			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));

		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("4".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));
		mainCond0.add(
			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("5".equals(dateTypeId)) {
		// 如果存在时间选择
		if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
		    mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO,
			    createTime_fld0_value));
		}
		if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
//		    mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO,
//			    createTime_fld1_value));

		    mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO,
			    UtilDateTime.getDayEnd(createTime_fld1_value)));
		}

	    }

	    List mainCondUpdateTime = new ArrayList();
	    if ("1".equals(dateTypeId)) {
		mainCondUpdateTime.add(
			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCondUpdateTime
			.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("2".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));
		mainCondUpdateTime.add(
			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCondUpdateTime
			.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));

	    } else if ("3".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-31));
		mainCondUpdateTime.add(
			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));

		mainCondUpdateTime
			.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("4".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));
		mainCondUpdateTime.add(
			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCondUpdateTime
			.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("5".equals(dateTypeId)) {
		// 如果存在时间选择
		if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
		    mainCondUpdateTime.add(EntityCondition.makeCondition("updateTime",
			    EntityOperator.GREATER_THAN_EQUAL_TO, createTime_fld0_value));
		}
		if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
		    mainCondUpdateTime.add(EntityCondition.makeCondition("updateTime",
			    EntityOperator.LESS_THAN_EQUAL_TO, createTime_fld1_value));
		}
	    }
	    mainCond0.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    List mainCond1 = new ArrayList();
	    mainCond1.addAll(mainCondUser);

	    mainCond1.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("5")));
	    mainCond1.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    if ("1".equals(dateTypeId)) {
		mainCond1.add(
			EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond1
			.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("2".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));
		mainCond1.add(
			EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond1
			.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));

	    } else if ("3".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-31));
		mainCond1.add(
			EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));

		mainCond1
			.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("4".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));
		mainCond1.add(
			EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond1
			.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("5".equals(dateTypeId)) {
		// 如果存在时间选择
		if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
		    mainCond1.add(EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO,
			    createTime_fld0_value));
		}
		if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
		    mainCond1.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO,
			    createTime_fld1_value));
		}
	    }

	    // 活跃客户 客户如果有成功入仓商机，就始终是活跃的客户。 不随着顶端的时间筛选而变。
	    List mainCond_active_customer = new ArrayList();
	    mainCond_active_customer.addAll(mainCondUser);

	    mainCond_active_customer.add(EntityCondition.makeCondition("infoStatusId", EntityOperator.EQUALS, "3"));
	    mainCond_active_customer.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    Long activeCustomerNum = delegator.findCountByCondition("CrmCustomer", EntityCondition.makeCondition(mainCond_active_customer, EntityOperator.AND), null, null);


	    // 沉默客户 不随着顶端的时间筛选而变。
	    // 1.1、客户名下无商机，且最近三个月内客户数据无更新；
	    // 1.2、客户名下有商机，客户数据最近三个月内无更新，且最近三个月内该客户名下所有的（非入仓状态的/非失败状态的）商机无更新；
	    List mainCond_six_month_customer = new ArrayList();
	    mainCond_six_month_customer.addAll(mainCondUser);

	    mainCond_six_month_customer
		    .add(EntityCondition.makeCondition("infoStatusId", EntityOperator.IN, UtilMisc.toList("1", "2")));
	    mainCond_six_month_customer.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    Long sixMonthCrmCustomerNum = delegator.findCountByCondition("CrmCustomer", EntityCondition.makeCondition(mainCond_six_month_customer, EntityOperator.AND), null, null);

	    // 活跃商机 （DB逻辑：3个月内有更新的（0~5状态）商机）； 活跃商机为0~5，包含5
	    // //成功商机为6 失败商机是7 //总商机数-沉默商机-入仓商机-失败商机
	    List mainCond_active_business = new ArrayList();
	    mainCond_active_business.addAll(mainCondUser);
	    mainCond_active_business.add(EntityCondition.makeCondition("infoStatusId", EntityOperator.EQUALS, "3"));

	    mainCond_active_business.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    Long activeBusinessNum = delegator.findCountByCondition("CrmBusiness", EntityCondition.makeCondition(mainCond_active_business, EntityOperator.AND), null, null);

	    // 沉默商机 最近三个月（非入仓状态的/非失败状态的）商机无更新； 沉默商机包含5和7状态
	    List mainCond_chengmo = new ArrayList();
	    mainCond_chengmo.addAll(mainCondUser);
	    mainCond_chengmo.add(EntityCondition.makeCondition("infoStatusId", EntityOperator.IN, UtilMisc.toList("1", "2")));

	    mainCond_chengmo.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

//	    Long sixMonthCrmBusinessNum = delegator.findCountByCondition("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond_chengmo, EntityOperator.AND), null, null);

	    Long sixMonthCrmBusinessNum = delegator.findCountByCondition("CrmBusiness",EntityCondition.makeCondition(mainCond_chengmo, EntityOperator.AND), null, null);
	    List newCrmBusinessList = new ArrayList();

	    // 活跃商机金额
	    Long newCrmBusinessTotalAmount = 0L;

	    List<GenericValue> crmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, UtilMisc.toList("-updateTime"),
		    null, true);
	    for (GenericValue crmBusiness : crmBusinessList) {

		String statusId = crmBusiness.getString("statusId");
		if ("5".equals(statusId) || "7".equals(statusId)) {
		    continue;
		}

		String businessId = crmBusiness.getString("id");
		Map param = UtilMisc.toMap("businessId", businessId);
		List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null, true);
		BigDecimal totalEstimatedSalesAmount = BigDecimal.ZERO;
		for (GenericValue crmBusinessItem : crmBusinessItemList) {
		    if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
			BigDecimal estimatedSalesAmount = crmBusinessItem.getBigDecimal("estimatedSalesAmount");
			totalEstimatedSalesAmount = totalEstimatedSalesAmount.add(estimatedSalesAmount);
		    }
		}
		newCrmBusinessTotalAmount = newCrmBusinessTotalAmount + totalEstimatedSalesAmount.longValue();

		Map m = new HashMap();
		m.putAll(crmBusiness);
		String customerId = crmBusiness.getString("customerId");
		if (UtilValidate.isNotEmpty(customerId)) {
		    GenericValue crmCustomer = delegator.findOne("CrmCustomer", true, UtilMisc.toMap("id", customerId));
		    if (UtilValidate.isNotEmpty(crmCustomer)) {
			m.put("customerId_dictText", crmCustomer.getString("customerName"));
		    }
		}
		newCrmBusinessList.add(m);
	    }

	    // 新签金额
	    Long successCrmBusinessTotalAmount = 0L;
	    List<GenericValue> successCrmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null, UtilMisc.toList("-updateTime"),
		    null, true);
	    for (GenericValue successCrmBusiness : successCrmBusinessList) {

		String businessId = successCrmBusiness.getString("id");
		Map param = UtilMisc.toMap("businessId", businessId);
		List<GenericValue> successCrmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null,
			true);
		BigDecimal successCrmBusiness_totalEstimatedSalesAmount = BigDecimal.ZERO;
		for (GenericValue successCrmBusinessItem : successCrmBusinessItemList) {
		    if (UtilValidate.isNotEmpty(successCrmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
			BigDecimal estimatedSalesAmount = successCrmBusinessItem.getBigDecimal("estimatedSalesAmount");
			successCrmBusiness_totalEstimatedSalesAmount = successCrmBusiness_totalEstimatedSalesAmount
				.add(estimatedSalesAmount);
		    }
		}
		successCrmBusinessTotalAmount = successCrmBusinessTotalAmount
			+ successCrmBusiness_totalEstimatedSalesAmount.longValue();
	    }
	    
	    // 新签合同
//	    Long successCrmBusinessNum = delegator.findCountByCondition("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null, null);
	    Long successCrmBusinessNum = new Long(successCrmBusinessList.size());

	    // 新签客户 选取的本时间段内，新增客户总数，去除该时段的沉默客户；
	    Long newCrmCustomerNum = delegator.findCountByCondition("CrmCustomer", EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, null);;

	    Map<String, Object> workMap = FastMap.newInstance();

	    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    String fromDateDateFormat = simpleDateFormat.format(fromDate);
	    String thruDateDateFormat = simpleDateFormat.format(thruDate);
	    if (UtilValidate.isNotEmpty(createTime_fld0_value) && dateTypeId.equals("5")) {
		workMap.put("fromDate", createTime_fld0_value);
	    } else {
		workMap.put("fromDate", fromDateDateFormat);
	    }
	    if (UtilValidate.isNotEmpty(createTime_fld1_value) && dateTypeId.equals("5")) {
		workMap.put("thruDate", createTime_fld1_value);
	    } else {
		workMap.put("thruDate", thruDateDateFormat);
	    }
	    if ("all".equals(dateTypeId)) {
		workMap.put("fromDate", "");
		workMap.put("thruDate", thruDateDateFormat);
	    }
	    workMap.put("activeCustomerNum", activeCustomerNum);

	    workMap.put("sixMonthCrmCustomerNum", sixMonthCrmCustomerNum);

	    workMap.put("activeBusinessNum", activeBusinessNum);

	    workMap.put("sixMonthCrmBusinessNum", sixMonthCrmBusinessNum);

	    workMap.put("newCrmBusinessTotalAmount", newCrmBusinessTotalAmount);

	    workMap.put("successCrmBusinessTotalAmount", successCrmBusinessTotalAmount);

	    workMap.put("successCrmBusinessNum", successCrmBusinessNum);

	    workMap.put("newCrmCustomerNum", newCrmCustomerNum);

	    result.put("workMap", workMap);

	    LocalDispatcher dispatcher = dctx.getDispatcher();

	    Map service_context = new HashMap<>();
	    service_context.put("objectId", ownerUserId);
	    service_context.put("userLogin", userLogin);

	    String personName = getPersonName(delegator, ownerUserId);
	    service_context.put("content", personName + ":" + ownerUserId + "登录记录  ");

	    dispatcher.runAsync("createWvVisitLog", service_context);

	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }
    
    /**
     * 仪表盘数据
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map<String, Object> getCrmDashBoardData(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");

	String ownerUserId = userLogin.getString("userLoginId");
	String personTypeId = (String) context.get("personTypeId");// 本人 ，本人及下属 //全国 大区 bu等等
	String dateTypeId = (String) context.get("dateTypeId");// 本日 ，本周，本月 ，本年
	Timestamp createTime_fld0_value = (Timestamp) context.get("createTime_fld0_value");
	Timestamp createTime_fld1_value = (Timestamp) context.get("createTime_fld1_value");

	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-1));
    Debug.log("590 = "+UtilDateTime.nowDateString());
	try {
	    List ownerUserIdList = new ArrayList();

	    List mainCondUser = new ArrayList();

	    if ("1".equals(personTypeId)) {// 本人
		ownerUserIdList.add(ownerUserId);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
	    } else if ("2".equals(personTypeId)) {// 本bu
		List<GenericValue> subordinateList = delegator.findByAnd("UserLogin",
			UtilMisc.toMap("superiorId", ownerUserId), null, true);
		for (GenericValue subordinate : subordinateList) {
		    String subordinateUserLoginId = subordinate.getString("userLoginId");
		    ownerUserIdList.add(subordinateUserLoginId);
		}
		ownerUserIdList.add(ownerUserId);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
	    } else if ("allData".equals(personTypeId)) { // 全国
		// ownerUserIdList.add(ownerUserId);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.NOT_EQUAL, "public"));
	    } else if ("3".equals(personTypeId)) { // 本大区
		// 先找到人属于那个bu.找到bu属于哪个大区.
		List<GenericValue> shipList = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdTo", ownerUserId), null, true);
		if (UtilValidate.isNotEmpty(shipList)) {
//		    // 获取buCode
		    String buCode = EntityUtil.getFirst(shipList).getString("partyIdFrom");
		    List<GenericValue> dataList1 = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("dictionaryCode", buCode), null, true);

		    GenericValue data1 = EntityUtil.getFirst(dataList1);
		    String areaId = data1.getString("parentId");
		    // 获取大区ID
		    if (UtilValidate.isNotEmpty(areaId)) {
			// 获取大区下的bu列表
			List<GenericValue> sunBuList = delegator.findByAnd("DataDictionary",
				UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT", "parentId", areaId), null, true);
			for (GenericValue bu : sunBuList) {
			    List<GenericValue> itemShipList = delegator.findByAnd("CoRelationship",
				    UtilMisc.toMap("partyIdFrom", bu.getString("dictionaryCode")), null, true);
			    for (GenericValue coRelationship : itemShipList) {
				String partyIdTo = coRelationship.getString("partyIdTo");
				ownerUserIdList.add(partyIdTo);
			    }
			}
		    }

		}
		ownerUserIdList.add(ownerUserId);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
	    } else if (isNumeric(personTypeId)) { // 人员
		ownerUserId = personTypeId;
		ownerUserIdList.add(ownerUserId);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
	    } else {
			List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
				UtilMisc.toMap("dictionaryCode", personTypeId), null, true);
			GenericValue data = EntityUtil.getFirst(dataList);
			
			if(UtilValidate.isNotEmpty(data)) {
				String dictionaryTypeId = data.getString("dictionaryTypeId");
				// 各大区
					if (dictionaryTypeId.equals("AREA_DEPARTMENT")) {
					    List<GenericValue> childList = delegator.findByAnd("DataDictionary",
						    UtilMisc.toMap("parentId", data.getString("dictionaryId")), null, true);
					    for (GenericValue child : childList) {
						String code = child.getString("dictionaryCode");
						List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
							UtilMisc.toMap("partyIdFrom", code), null, true);
						for (GenericValue coRelationship : coRelationshipList) {
						    String partyIdTo = coRelationship.getString("partyIdTo");
						    ownerUserIdList.add(partyIdTo);
						}
					    }
					    mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
			
					} else {
					    // 各bu
					    List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
						    UtilMisc.toMap("partyIdFrom", personTypeId), null, true);
					    for (GenericValue coRelationship : coRelationshipList) {
						String partyIdTo = coRelationship.getString("partyIdTo");
						ownerUserIdList.add(partyIdTo);
					    }
					    mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
			
					}
			}
			
	    }
	    Debug.log("681 = "+UtilDateTime.nowDateString());
	    List mainCond0 = new ArrayList();
	    mainCond0.addAll(mainCondUser);
	    if ("1".equals(dateTypeId)) {
		mainCond0.add(
			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("2".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));
		mainCond0.add(
			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));

	    } else if ("3".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-31));
		mainCond0.add(
			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));

		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("4".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));
		mainCond0.add(
			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("5".equals(dateTypeId)) {
		// 如果存在时间选择
		if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
		    mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO,
			    createTime_fld0_value));
		}
		if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
//		    mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO,
//			    createTime_fld1_value));

		    mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO,
			    UtilDateTime.getDayEnd(createTime_fld1_value)));
		}

	    }

	    List mainCondUpdateTime = new ArrayList();
	    if ("1".equals(dateTypeId)) {
		mainCondUpdateTime.add(
			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCondUpdateTime
			.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("2".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));
		mainCondUpdateTime.add(
			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCondUpdateTime
			.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));

	    } else if ("3".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-31));
		mainCondUpdateTime.add(
			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));

		mainCondUpdateTime
			.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("4".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));
		mainCondUpdateTime.add(
			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCondUpdateTime
			.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("5".equals(dateTypeId)) {
		// 如果存在时间选择
		if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
		    mainCondUpdateTime.add(EntityCondition.makeCondition("updateTime",
			    EntityOperator.GREATER_THAN_EQUAL_TO, createTime_fld0_value));
		}
		if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
		    mainCondUpdateTime.add(EntityCondition.makeCondition("updateTime",
			    EntityOperator.LESS_THAN_EQUAL_TO, createTime_fld1_value));
		}
	    }
	    mainCond0.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    List mainCond1 = new ArrayList();
	    mainCond1.addAll(mainCondUser);

	    mainCond1.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("5")));
	    mainCond1.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    if ("1".equals(dateTypeId)) {
		mainCond1.add(
			EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond1
			.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("2".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));
		mainCond1.add(
			EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond1
			.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));

	    } else if ("3".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-31));
		mainCond1.add(
			EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));

		mainCond1
			.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("4".equals(dateTypeId)) {
		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));
		mainCond1.add(
			EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond1
			.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    } else if ("5".equals(dateTypeId)) {
		// 如果存在时间选择
		if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
		    mainCond1.add(EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO,
			    createTime_fld0_value));
		}
		if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
		    mainCond1.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO,
			    createTime_fld1_value));
		}
	    }

	    // 活跃客户 客户如果有成功入仓商机，就始终是活跃的客户。 不随着顶端的时间筛选而变。
	    List mainCond_active_customer = new ArrayList();
	    mainCond_active_customer.addAll(mainCondUser);

	    mainCond_active_customer.add(EntityCondition.makeCondition("infoStatusId", EntityOperator.EQUALS, "3"));
	    mainCond_active_customer.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

//	    Long activeCustomerNum = delegator.findCountByCondition("CrmCustomer",
//		    EntityCondition.makeCondition(mainCond_active_customer, EntityOperator.AND), null, null);
	    Debug.log("812 = "+UtilDateTime.nowDateString()+" = map_activeCustomerList");
	    List map_activeCustomerList = delegator.findList("CrmCustomer",
		    EntityCondition.makeCondition(mainCond_active_customer, EntityOperator.AND), null,
		    UtilMisc.toList("-createdStamp"), null, true);
	    Long activeCustomerNum = new Long(map_activeCustomerList.size());
	    Debug.log("817 = "+UtilDateTime.nowDateString()+" = buildCrmCustomerMap");
	    List<Map<String, Object>> activeCustomerList = buildCrmCustomerMap(map_activeCustomerList);
	    Debug.log("819 = "+UtilDateTime.nowDateString()+" = buildCrmCustomerMap");
	    // 按商机金额排序
	    Collections.sort(activeCustomerList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = Integer.valueOf((int) ((Long) obj2.get("businessTotalAmount")).doubleValue())
			    .compareTo(Integer.valueOf((int) ((Long) obj1.get("businessTotalAmount")).doubleValue()));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    // 沉默客户 不随着顶端的时间筛选而变。
	    // 1.1、客户名下无商机，且最近三个月内客户数据无更新；
	    // 1.2、客户名下有商机，客户数据最近三个月内无更新，且最近三个月内该客户名下所有的（非入仓状态的/非失败状态的）商机无更新；
	    List mainCond_six_month_customer = new ArrayList();
	    mainCond_six_month_customer.addAll(mainCondUser);

	    mainCond_six_month_customer
		    .add(EntityCondition.makeCondition("infoStatusId", EntityOperator.IN, UtilMisc.toList("1", "2")));
	    mainCond_six_month_customer.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

//	    Long sixMonthCrmCustomerNum = delegator.findCountByCondition("CrmCustomer",
//		    EntityCondition.makeCondition(mainCond_six_month_customer, EntityOperator.AND), null, null);
	    Debug.log("842 = "+UtilDateTime.nowDateString()+" = map_sixMonthCrmCustomerList");
	    List map_sixMonthCrmCustomerList = delegator.findList("CrmCustomer",
		    EntityCondition.makeCondition(mainCond_six_month_customer, EntityOperator.AND), null,
		    UtilMisc.toList("-createdStamp"), null, true);
	    Long sixMonthCrmCustomerNum = new Long(map_sixMonthCrmCustomerList.size());
	    Debug.log("847 = "+UtilDateTime.nowDateString()+" = buildCrmCustomerMap");
	    List<Map<String, Object>> sixMonthCrmCustomerList = buildCrmCustomerMap(map_sixMonthCrmCustomerList);
	    Debug.log("849 = "+UtilDateTime.nowDateString()+" = buildCrmCustomerMap");
	    // 按商机金额排序
	    Collections.sort(sixMonthCrmCustomerList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = Integer.valueOf((int) ((Long) obj2.get("businessTotalAmount")).doubleValue())
			    .compareTo(Integer.valueOf((int) ((Long) obj1.get("businessTotalAmount")).doubleValue()));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    // 活跃商机 （DB逻辑：3个月内有更新的（0~5状态）商机）； 活跃商机为0~5，包含5
	    // //成功商机为6 失败商机是7 //总商机数-沉默商机-入仓商机-失败商机
	    List mainCond_active_business = new ArrayList();
	    mainCond_active_business.addAll(mainCondUser);
	    mainCond_active_business.add(EntityCondition.makeCondition("infoStatusId", EntityOperator.EQUALS, "3"));

	    mainCond_active_business.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

//	    Long activeBusinessNum = delegator.findCountByCondition("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond_active_business, EntityOperator.AND), null, null);
	    Debug.log("870 = "+UtilDateTime.nowDateString()+" = activeBusinessList");
	    List activeBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond_active_business, EntityOperator.AND), null,
		    UtilMisc.toList("-updateTime"), null, true);
	    Long activeBusinessNum = new Long(activeBusinessList.size());
	    Debug.log("875 = "+UtilDateTime.nowDateString()+" = buildCrmBusiness");
	    activeBusinessList = buildCrmBusiness(activeBusinessList);
	    Debug.log("877 = "+UtilDateTime.nowDateString()+" = buildCrmBusiness");
	    // 沉默商机 最近三个月（非入仓状态的/非失败状态的）商机无更新； 沉默商机包含5和7状态
	    List mainCond_chengmo = new ArrayList();
	    mainCond_chengmo.addAll(mainCondUser);
	    mainCond_chengmo
		    .add(EntityCondition.makeCondition("infoStatusId", EntityOperator.IN, UtilMisc.toList("1", "2")));

	    mainCond_chengmo.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

//	    Long sixMonthCrmBusinessNum = delegator.findCountByCondition("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond_chengmo, EntityOperator.AND), null, null);
	    Debug.log("888 = "+UtilDateTime.nowDateString()+" = sixMonthCrmBusinessList");
	    List sixMonthCrmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond_chengmo, EntityOperator.AND), null,
		    UtilMisc.toList("-updateTime"), null, true);
	    Long sixMonthCrmBusinessNum = new Long(sixMonthCrmBusinessList.size());
	    Debug.log("893 = "+UtilDateTime.nowDateString()+" = sixMonthCrmBusinessList");
	    sixMonthCrmBusinessList = buildCrmBusiness(sixMonthCrmBusinessList);
	    Debug.log("895 = "+UtilDateTime.nowDateString()+" = sixMonthCrmBusinessList");
	    List newCrmBusinessList = new ArrayList();

	    // 活跃商机金额
	    Long newCrmBusinessTotalAmount = 0L;
	    Debug.log("900 = "+UtilDateTime.nowDateString()+" = crmBusinessList");
	    List<GenericValue> crmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, UtilMisc.toList("-updateTime"),
		    null, true);
	    Debug.log("904 = "+UtilDateTime.nowDateString()+" = crmBusinessList");
	    for (GenericValue crmBusiness : crmBusinessList) {

		String statusId = crmBusiness.getString("statusId");
		if ("5".equals(statusId) || "7".equals(statusId)) {
		    continue;
		}

		String businessId = crmBusiness.getString("id");
		Map param = UtilMisc.toMap("businessId", businessId);
		List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null, true);
		BigDecimal totalEstimatedSalesAmount = BigDecimal.ZERO;
		for (GenericValue crmBusinessItem : crmBusinessItemList) {
		    if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
			BigDecimal estimatedSalesAmount = crmBusinessItem.getBigDecimal("estimatedSalesAmount");
			totalEstimatedSalesAmount = totalEstimatedSalesAmount.add(estimatedSalesAmount);
		    }
		}
		newCrmBusinessTotalAmount = newCrmBusinessTotalAmount + totalEstimatedSalesAmount.longValue();

		Map m = new HashMap();
		m.putAll(crmBusiness);
		String customerId = crmBusiness.getString("customerId");
		if (UtilValidate.isNotEmpty(customerId)) {
		    GenericValue crmCustomer = delegator.findOne("CrmCustomer", true, UtilMisc.toMap("id", customerId));
		    if (UtilValidate.isNotEmpty(crmCustomer)) {
			m.put("customerId_dictText", crmCustomer.getString("customerName"));
		    }
		}
		newCrmBusinessList.add(m);
	    }
	    Debug.log("935 = "+UtilDateTime.nowDateString()+" = buildCrmBusinessMap");
	    List newCrmBusinessTotalAmountList = buildCrmBusinessMap(delegator, newCrmBusinessList);
	    Debug.log("937 = "+UtilDateTime.nowDateString()+" = buildCrmBusinessMap");
	    // 新签金额
	    Long successCrmBusinessTotalAmount = 0L;
	    List<GenericValue> successCrmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null, UtilMisc.toList("-updateTime"),
		    null, true);
	    
	    Debug.log("944 = "+UtilDateTime.nowDateString()+" = successCrmBusinessList");
	    for (GenericValue successCrmBusiness : successCrmBusinessList) {

		String businessId = successCrmBusiness.getString("id");
		Map param = UtilMisc.toMap("businessId", businessId);
		List<GenericValue> successCrmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null,
			true);
		BigDecimal successCrmBusiness_totalEstimatedSalesAmount = BigDecimal.ZERO;
		for (GenericValue successCrmBusinessItem : successCrmBusinessItemList) {
		    if (UtilValidate.isNotEmpty(successCrmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
			BigDecimal estimatedSalesAmount = successCrmBusinessItem.getBigDecimal("estimatedSalesAmount");
			successCrmBusiness_totalEstimatedSalesAmount = successCrmBusiness_totalEstimatedSalesAmount
				.add(estimatedSalesAmount);
		    }
		}
		successCrmBusinessTotalAmount = successCrmBusinessTotalAmount
			+ successCrmBusiness_totalEstimatedSalesAmount.longValue();

	    }
	    Debug.log("963 = "+UtilDateTime.nowDateString()+" = successCrmBusinessList");
	    List successCrmBusinessTotalAmountList = buildCrmBusiness(successCrmBusinessList);
	    Debug.log("965 = "+UtilDateTime.nowDateString()+" = successCrmBusinessTotalAmountList");
	    // 新签合同
//	    Long successCrmBusinessNum = delegator.findCountByCondition("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null, null);
	    Long successCrmBusinessNum = new Long(successCrmBusinessList.size());
	    List successCrmBusinessList1 = buildCrmBusiness(successCrmBusinessList);
	    Debug.log("971 = "+UtilDateTime.nowDateString()+" = successCrmBusinessList1");
	    // 新签客户 选取的本时间段内，新增客户总数，去除该时段的沉默客户；
//	    Long newCrmCustomerNum = delegator.findCountByCondition("CrmCustomer",
//		    EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, null);

	    List newCrmCustomerList = delegator.findList("CrmCustomer",
		    EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null,
		    UtilMisc.toList("-createdStamp"), null, true);
	    Long newCrmCustomerNum = new Long(newCrmCustomerList.size());
	    Debug.log("980 = "+UtilDateTime.nowDateString()+" = newCrmCustomerList");
	    List newCrmCustomerList1 = buildCrmCustomerMap(newCrmCustomerList);
	    Debug.log("982 = "+UtilDateTime.nowDateString()+" = newCrmCustomerList1");

	    Collections.sort(newCrmCustomerList1, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = ((Timestamp) obj2.get("updateTime")).compareTo((Timestamp) obj1.get("updateTime"));
		    return i;
		}
	    });

	    Map<String, Object> workMap = FastMap.newInstance();

	    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    String fromDateDateFormat = simpleDateFormat.format(fromDate);
	    String thruDateDateFormat = simpleDateFormat.format(thruDate);
	    if (UtilValidate.isNotEmpty(createTime_fld0_value) && dateTypeId.equals("5")) {
		workMap.put("fromDate", createTime_fld0_value);
	    } else {
		workMap.put("fromDate", fromDateDateFormat);
	    }
	    if (UtilValidate.isNotEmpty(createTime_fld1_value) && dateTypeId.equals("5")) {
		workMap.put("thruDate", createTime_fld1_value);
	    } else {
		workMap.put("thruDate", thruDateDateFormat);
	    }
	    if ("all".equals(dateTypeId)) {
		workMap.put("fromDate", "");
		workMap.put("thruDate", thruDateDateFormat);
	    }
	    workMap.put("activeCustomerNum", activeCustomerNum);
	    workMap.put("activeCustomerList", activeCustomerList);

	    workMap.put("sixMonthCrmCustomerNum", sixMonthCrmCustomerNum);
	    workMap.put("sixMonthCrmCustomerList", sixMonthCrmCustomerList);

	    workMap.put("activeBusinessNum", activeBusinessNum);
	    workMap.put("activeBusinessList", activeBusinessList);

	    workMap.put("sixMonthCrmBusinessNum", sixMonthCrmBusinessNum);
	    workMap.put("sixMonthCrmBusinessList", sixMonthCrmBusinessList);

	    workMap.put("newCrmBusinessTotalAmount", newCrmBusinessTotalAmount);
	    workMap.put("newCrmBusinessTotalAmountList", newCrmBusinessTotalAmountList);

	    workMap.put("successCrmBusinessTotalAmount", successCrmBusinessTotalAmount);
	    workMap.put("successCrmBusinessTotalAmountList", successCrmBusinessTotalAmountList);

	    workMap.put("successCrmBusinessNum", successCrmBusinessNum);
	    workMap.put("successCrmBusinessList", successCrmBusinessList1);

	    workMap.put("newCrmCustomerNum", newCrmCustomerNum);
	    workMap.put("newCrmCustomerList", newCrmCustomerList1);

	    Debug.log("1035 = "+UtilDateTime.nowDateString()+" = crmBusinessCustRankingMap");
	    // 活跃商机排行榜
	    workMap.put("crmBusinessCustRankingMap",
		    crmBusinessCustRankingMap(delegator, newCrmBusinessTotalAmountList));
	    Debug.log("1039 = "+UtilDateTime.nowDateString()+" = crmBusinessCustRankingMap");
	    result.put("workMap", workMap);

	    LocalDispatcher dispatcher = dctx.getDispatcher();

	    Map service_context = new HashMap<>();
	    service_context.put("objectId", ownerUserId);
	    service_context.put("userLogin", userLogin);

	    String personName = getPersonName(delegator, ownerUserId);
	    service_context.put("content", personName + ":" + ownerUserId + "登录记录  ");

	    dispatcher.runAsync("createWvVisitLog", service_context);

	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	    return ServiceUtil.returnError(e.getMessage());
	}
	return result;
    }

    
    
    
    
    
    
    @SuppressWarnings("rawtypes")
    public static Map crmBusinessCustRankingMap(Delegator delegator, List businessList) {

	Map<String, Object> result = new HashMap<>();

	Map invDataCollection = new HashMap();
	Map personDataCollection = new HashMap();
	Map buDataCollection = new HashMap();
	List<Map> invDataList = new ArrayList();
	List<Map> personDataList = new ArrayList();
	List<Map> buDataList = new ArrayList();

	try {

	    for (int i = 0; i < businessList.size(); i++) {
		Map crmBusiness = (Map) businessList.get(i);

		String statusId = (String) crmBusiness.get("statusId");
		String businessId = (String) crmBusiness.get("id");
		String ownerUserId = (String) crmBusiness.get("ownerUserId");
		String warehouseName = (String) crmBusiness.get("warehouseName");
		String inventoryId = (String) crmBusiness.get("inventoryId");
		BigDecimal estimatedSalesAmount = (BigDecimal) crmBusiness.get("estimatedSalesAmount");
//    		if ("public".equals(ownerUserId)) {
//    		    continue;
//    		}
//    		Map param = UtilMisc.toMap("businessId", businessId);

		if ("5".equals(statusId) || "7".equals(statusId)) {
		    continue;
		}

		Map personData = new HashMap();
		personData.put("ownerUserId", ownerUserId);
		personData.put("estimatedSalesAmount", estimatedSalesAmount);
		personData.put("warehouseName", warehouseName);
		personData.put("inventoryId", inventoryId);
		// Debug.log("personDataCollection = " + personDataCollection);
		// Debug.log("personData = " + personData);
		personDataCollection = addPersonDataCollectionBusinessNum1(delegator, personDataCollection, personData);
		// Debug.log("buDataCollection = " + buDataCollection);

		buDataCollection = addBuDataCollectionBusinessNum1(delegator, buDataCollection, personData);

		invDataCollection = addInvDataCollectionBusinessNum1(delegator, invDataCollection, personData);

	    }

	    personDataList = new ArrayList<Map>(personDataCollection.values());
	    buDataList = new ArrayList<Map>(buDataCollection.values());
	    invDataList = new ArrayList<Map>(invDataCollection.values());

	    personDataList = isNullPersonName(personDataList);
	    invDataList = isNullWarehouseName(invDataList);
	    buDataList = isNullBuName(buDataList);

	    // 按照商机金额进行排序
	    Collections.sort(invDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = Integer.valueOf((int) ((BigDecimal) obj2.get("estimatedSalesAmount")).doubleValue())
			    .compareTo(Integer
				    .valueOf((int) ((BigDecimal) obj1.get("estimatedSalesAmount")).doubleValue()));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });
	    // 按照商机金额进行排序
	    Collections.sort(personDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = Integer.valueOf((int) ((BigDecimal) obj2.get("estimatedSalesAmount")).doubleValue())
			    .compareTo(Integer
				    .valueOf((int) ((BigDecimal) obj1.get("estimatedSalesAmount")).doubleValue()));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    // 按照商机金额进行排序
	    Collections.sort(buDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = Integer.valueOf((int) ((BigDecimal) obj2.get("estimatedSalesAmount")).doubleValue())
			    .compareTo(Integer
				    .valueOf((int) ((BigDecimal) obj1.get("estimatedSalesAmount")).doubleValue()));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

//    	    List<Map> personNewDataList = new ArrayList();
//    	    for (Map personData : personDataList) {
//    		Map personData2 = new HashMap();
//    		personData2.put("buName", personData.get("buName"));
//    		personData2.put("ownerUserId", personData.get("ownerUserId"));
//    		personData2.put("personName", personData.get("personName"));
//    		personData2.put("estimatedSalesAmount", personData.get("estimatedSalesAmount"));
//    		personNewDataList.add(personData2);
//    	    }
//    	    List<Map> buDataNewList = new ArrayList();
//    	    for (Map buData : buDataList) {
//    		Map buData2 = new HashMap();
//    		buData2.put("buName", buData.get("buName"));
//    		buData2.put("buId", buData.get("buId"));
//    		buData2.put("estimatedSalesAmount", buData.get("estimatedSalesAmount"));
//    		buDataNewList.add(buData2);
//    	    }
//
//    	    List<Map> invDataNewList = new ArrayList();
//    	    for (Map invData : invDataList) {
//    		Map invData2 = new HashMap();
//    		invData2.put("warehouseName", invData.get("warehouseName"));
//    		invData2.put("inventoryId", invData.get("inventoryId"));
//    		invData2.put("estimatedSalesAmount", invData.get("estimatedSalesAmount"));
//    		invDataNewList.add(invData2);
//    	    }
	    // Debug.log("buDataList = " + buDataNewList);
//    	    result.put("invDataList", invDataNewList);
//    	    result.put("personDataList", personNewDataList);
//    	    result.put("buDataList", buDataNewList);

	    result.put("invDataList", invDataList);
	    result.put("personDataList", personDataList);
	    result.put("buDataList", buDataList);
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	// result.put("workMap", workMap);
	// Debug.log("result ===" + result);
	return result;
    }

    private static List isNullPersonName(List<Map> list) {
	List result = new ArrayList();
	for (Map map : list) {
	    if (UtilValidate.isNotEmpty(map.get("personName"))) {
		result.add(map);
	    }
	}
	return result;
    }

    private static List isNullWarehouseName(List<Map> list) {
	List result = new ArrayList();
	for (Map map : list) {
	    if (UtilValidate.isNotEmpty(map.get("warehouseName"))) {
		result.add(map);
	    }
	}
	return result;
    }

    private static List isNullBuName(List<Map> list) {
	List result = new ArrayList();
	for (Map map : list) {
	    if (UtilValidate.isNotEmpty(map.get("buName"))) {
		result.add(map);
	    }
	}
	return result;
    }

    public static List buildCrmCustomerMap(List<GenericValue> inCustomerList) throws GenericEntityException {
	List result = new ArrayList();
	Delegator delegator = DelegatorFactory.getDelegator("default");
	// , "dictionaryCode", partyIdFrom
	List<GenericValue> dataDictionaryInfo = delegator.findByAnd("DataDictionary",
		UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT"), null, true);
	Map<String, Object> map1 = FastMap.newInstance();

	for (GenericValue dataDictionary : dataDictionaryInfo) {
	    map1.put(dataDictionary.getString("dictionaryId"), dataDictionary.getString("description"));
	}

	List<GenericValue> dataDictionaryInfo2 = delegator.findByAnd("DataDictionary",
		UtilMisc.toMap("dictionaryTypeId", "PRODUCT_CATEGORY"), null, true);

	Map<String, Object> map2 = FastMap.newInstance();
	for (GenericValue dataDictionary2 : dataDictionaryInfo2) {
	    map2.put(dataDictionary2.getString("dictionaryCode"), dataDictionary2.getString("description"));
	}
	for (GenericValue inCustomer : inCustomerList) {
	    String id = inCustomer.getString("id");
	    String ownerUserId = inCustomer.getString("ownerUserId");
	    String relatedCustomer = inCustomer.getString("relatedCustomer");
	    Map map = new HashMap();
	    map.putAll(inCustomer);
//	    map.remove("remark");

//	    Debug.log("buildCrmBusiness ownerUserId= " + ownerUserId);
	    if (UtilValidate.isNotEmpty(ownerUserId) && !"public".equals(ownerUserId)) {
		GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", ownerUserId),
			true);
		if (UtilValidate.isNotEmpty(userLogin)) {
		    GenericValue person = delegator.findOne("Person",
			    UtilMisc.toMap("partyId", userLogin.getString("partyId")), true);
		    if (UtilValidate.isNotEmpty(person)) {
			String ownerUserId_dictText = person.getString("name");
			map.put("ownerUserId_dictText", ownerUserId_dictText);
//			Debug.log("buildCrmBusiness ownerUserId_dictText= " + ownerUserId_dictText);
		    }
		}

		if (UtilValidate.isNotEmpty(relatedCustomer)) {
		    GenericValue customer = delegator.findOne("CrmCustomer",
			    UtilMisc.toMap("id", inCustomer.getString("relatedCustomer")), true);
		    if (UtilValidate.isNotEmpty(customer)) {
			String relatedCustomer_dictText = customer.getString("customerName");
			map.put("relatedCustomer_dictText", relatedCustomer_dictText);
		    }
		}

		List<GenericValue> coRelationshipInfo = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdTo", ownerUserId), null, true);
		GenericValue coRelationship = EntityUtil.getFirst(coRelationshipInfo);

		if (UtilValidate.isNotEmpty(coRelationship)) {
		    String partyIdFrom = coRelationship.getString("partyIdFrom");

//		    List<GenericValue> dataDictionaryInfo = delegator.findByAnd("DataDictionary",
//			    UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT", "dictionaryCode", partyIdFrom), null,
//			    true);
//		    GenericValue dataDictionary = EntityUtil.getFirst(dataDictionaryInfo);
		    if (UtilValidate.isNotEmpty(map1)) {
			if (UtilValidate.isNotEmpty(map1.get(partyIdFrom))) {
			    map.put("bu_dictText", map1.get(partyIdFrom));
			}
		    }
		}
	    }

	    // 产品分类
	    String productCategory = inCustomer.getString("productCategory");
	    if (UtilValidate.isNotEmpty(productCategory)) {
		if (UtilValidate.isNotEmpty(map2)) {
		    if (UtilValidate.isNotEmpty(map2.get(productCategory))) {
			map.put("productCategory_dictText", map2.get(productCategory));
		    }
		}
//		GenericValue gv = delegator.findOne("DataDictionary", true,
//			UtilMisc.toMap("dictionaryId", productCategory));
//		map.put("productCategory_dictText", gv.getString("description"));
	    }
	    // 客户状态
	    String infoStatusId = inCustomer.getString("infoStatusId");
	    if ("1".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "沉默");
	    } else if ("2".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "待激活");
	    } else if ("3".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "活跃");
	    } else if ("4".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "已删除");
	    }

	    // 商机类型
	    map.put("businessTypId_dictText", CrmServices.getBusinessTypeNameByCustomerId(id));
	    // 商机类型
	    // 全温区需求
	    BigDecimal estimatedFreeze = BigDecimal.ZERO;
	    BigDecimal estimatedRefrigerate = BigDecimal.ZERO;
	    BigDecimal estimatedConstant = BigDecimal.ZERO;
	    BigDecimal estimatedNormal = BigDecimal.ZERO;

	    // 商机金额
	    Long newCrmBusinessTotalAmount = 0L;

	    List<GenericValue> crmBusinessList = delegator.findByAnd("CrmBusiness",
		    UtilMisc.toMap("customerId", id, "removed", "N"), UtilMisc.toList("-createTime"), true);
	    for (GenericValue crmBusiness : crmBusinessList) {
		String businessId = crmBusiness.getString("id");
		Map param = UtilMisc.toMap("businessId", businessId);
		List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null, true);
		BigDecimal totalEstimatedSalesAmount = BigDecimal.ZERO;
		for (GenericValue crmBusinessItem : crmBusinessItemList) {
		    if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
			BigDecimal estimatedSalesAmount = crmBusinessItem.getBigDecimal("estimatedSalesAmount");
			totalEstimatedSalesAmount = totalEstimatedSalesAmount.add(estimatedSalesAmount);

			if (UtilValidate.isNotEmpty(crmBusinessItem.get("estimatedFreeze"))) {
			    estimatedFreeze = estimatedFreeze.add((BigDecimal) crmBusinessItem.get("estimatedFreeze"));
			}
			if (UtilValidate.isNotEmpty(crmBusinessItem.get("estimatedRefrigerate"))) {
			    estimatedRefrigerate = estimatedRefrigerate
				    .add((BigDecimal) crmBusinessItem.get("estimatedRefrigerate"));
			}
			if (UtilValidate.isNotEmpty(crmBusinessItem.get("estimatedConstant"))) {
			    estimatedConstant = estimatedConstant
				    .add((BigDecimal) crmBusinessItem.get("estimatedConstant"));
			}
			if (UtilValidate.isNotEmpty(crmBusinessItem.get("estimatedNormal"))) {
			    estimatedNormal = estimatedNormal.add((BigDecimal) crmBusinessItem.get("estimatedNormal"));
			}

		    }
		}
		newCrmBusinessTotalAmount = newCrmBusinessTotalAmount + totalEstimatedSalesAmount.longValue();
	    }
	    map.put("businessTotalAmount", newCrmBusinessTotalAmount);

	    map.put("estimatedAll",
		    estimatedFreeze.add(estimatedRefrigerate).add(estimatedConstant).add(estimatedNormal));
	    result.add(map);
	}

	return result;
    }

//    /**
//     * 仪表盘数据
//     */
//    @SuppressWarnings("unchecked")
//    public static Map<String, Object> getCrmDashBoardData(DispatchContext dctx, Map<String, ? extends Object> context) {
//	Map<String, Object> result = ServiceUtil.returnSuccess();
//	Delegator delegator = dctx.getDelegator();
//	GenericValue userLogin = (GenericValue) context.get("userLogin");
//
//	String ownerUserId = userLogin.getString("userLoginId");
//	String personTypeId = (String) context.get("personTypeId");// 本人 ，本人及下属 //全国 大区 bu等等
//	String dateTypeId = (String) context.get("dateTypeId");// 本日 ，本周，本月 ，本年
////		String dateCardTypeId = (String) context.get("dateCardTypeId");//近30天，近一年
//	Timestamp createTime_fld0_value = (Timestamp) context.get("createTime_fld0_value");
//	Timestamp createTime_fld1_value = (Timestamp) context.get("createTime_fld1_value");
//	try {
//	    List ownerUserIdList = new ArrayList();
//
//	    List mainCondUser = new ArrayList();
//
//	    if ("1".equals(personTypeId)) {// 本人
//		ownerUserIdList.add(ownerUserId);
//		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
//	    } else if ("2".equals(personTypeId)) {// 本bu
//		List<GenericValue> subordinateList = delegator.findByAnd("UserLogin",
//			UtilMisc.toMap("superiorId", ownerUserId), null, false);
//		for (GenericValue subordinate : subordinateList) {
//		    String subordinateUserLoginId = subordinate.getString("userLoginId");
//		    ownerUserIdList.add(subordinateUserLoginId);
//		}
//		ownerUserIdList.add(ownerUserId);
//		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
//	    } else if ("allData".equals(personTypeId)) { // 全国
//		// ownerUserIdList.add(ownerUserId);
//		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.NOT_EQUAL, "public"));
//	    } else if ("3".equals(personTypeId)) { // 本大区
//		// 先找到人属于那个bu.找到bu属于哪个大区.
//		List<GenericValue> shipList = delegator.findByAnd("CoRelationship",
//			UtilMisc.toMap("partyIdTo", ownerUserId), null, false);
//		if (UtilValidate.isNotEmpty(shipList)) {
////		    // 获取buCode
//		    String buCode = EntityUtil.getFirst(shipList).getString("partyIdFrom");
//		    List<GenericValue> dataList1 = delegator.findByAnd("DataDictionary",
//			    UtilMisc.toMap("dictionaryCode", buCode), null, false);
//
//		    GenericValue data1 = EntityUtil.getFirst(dataList1);
//		    String areaId = data1.getString("parentId");
//		    // 获取大区ID
//		    if (UtilValidate.isNotEmpty(areaId)) {
//			// 获取大区下的bu列表
//			List<GenericValue> sunBuList = delegator.findByAnd("DataDictionary",
//				UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT", "parentId", areaId), null, false);
//			for (GenericValue bu : sunBuList) {
//			    List<GenericValue> itemShipList = delegator.findByAnd("CoRelationship",
//				    UtilMisc.toMap("partyIdFrom", bu.getString("dictionaryCode")), null, false);
//			    for (GenericValue coRelationship : itemShipList) {
//				String partyIdTo = coRelationship.getString("partyIdTo");
//				ownerUserIdList.add(partyIdTo);
//			    }
//			}
//		    }
//
//		}
//
////		List<GenericValue> shipList = delegator.findByAnd("CoRelationship",
////			UtilMisc.toMap("partyIdTo", ownerUserId),null, false);
////		if (UtilValidate.isNotEmpty(shipList)) {
////		    // 获取本大区ID
////		    String areaCode = EntityUtil.getFirst(shipList).getString("partyIdFrom");
////		    if (UtilValidate.isNotEmpty(areaCode)) {
////			List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
////				UtilMisc.toMap("dictionaryCode", areaCode), null, false);
////			GenericValue data = EntityUtil.getFirst(dataList);
////			// 获取大区下的bu列表
////			List<GenericValue> sunBuList = delegator.findByAnd("DataDictionary",
////				UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT", "parentId", data.getString("dictionaryId")), null, false);
////			for (GenericValue bu : sunBuList) {
////			    List<GenericValue> itemShipList = delegator.findByAnd("CoRelationship",
////				    UtilMisc.toMap("partyIdFrom", bu.getString("dictionaryCode")), null, false);
////			    for (GenericValue coRelationship : itemShipList) {
////				String partyIdTo = coRelationship.getString("partyIdTo");
////				ownerUserIdList.add(partyIdTo);
////			    }
////			}
////		    }
////		}
//		ownerUserIdList.add(ownerUserId);
//		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
//	    } else if (isNumeric(personTypeId)) { // 人员
//		ownerUserId = personTypeId;
//		ownerUserIdList.add(ownerUserId);
//		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
//	    } else {
//		List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
//			UtilMisc.toMap("dictionaryCode", personTypeId), null, false);
//		GenericValue data = EntityUtil.getFirst(dataList);
//		String dictionaryTypeId = data.getString("dictionaryTypeId");
//		// 各大区
//		if (dictionaryTypeId.equals("AREA_DEPARTMENT")) {
//		    List<GenericValue> childList = delegator.findByAnd("DataDictionary",
//			    UtilMisc.toMap("parentId", data.getString("dictionaryId")), null, false);
//		    for (GenericValue child : childList) {
//			String code = child.getString("dictionaryCode");
//			List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
//				UtilMisc.toMap("partyIdFrom", code), null, false);
//			for (GenericValue coRelationship : coRelationshipList) {
//			    String partyIdTo = coRelationship.getString("partyIdTo");
//			    ownerUserIdList.add(partyIdTo);
//			}
//		    }
//		    mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
//
//		} else {
//		    // 各bu
//		    List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
//			    UtilMisc.toMap("partyIdFrom", personTypeId), null, false);
//		    for (GenericValue coRelationship : coRelationshipList) {
//			String partyIdTo = coRelationship.getString("partyIdTo");
//			ownerUserIdList.add(partyIdTo);
//		    }
//		    mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
//
//		}
//	    }
//
//	    List mainCond0 = new ArrayList();
//	    mainCond0.addAll(mainCondUser);
////			//本日 ，本周，本月 ，本年
////			Date date = new Date();
////			Calendar cal1 = Calendar.getInstance();
////			cal1.setTime(date);
////			// 将时分秒,毫秒域清零
////			cal1.set(Calendar.HOUR_OF_DAY, 0);
////			cal1.set(Calendar.MINUTE, 0);
////			cal1.set(Calendar.SECOND, 0);
////			cal1.add(Calendar.DATE, 0);
////			date = cal1.getTime();
////			// 查询当日应该是今天到明天为止
////			Timestamp thruDate = new Timestamp(date.getTime());
//	    Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
//	    Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-1));
//	    if ("1".equals(dateTypeId)) {
//		mainCond0.add(
//			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN, thruDate));
//	    } else if ("2".equals(dateTypeId)) {
//		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));
//		mainCond0.add(
//			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN, thruDate));
//
//	    } else if ("3".equals(dateTypeId)) {
//		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-31));
//		mainCond0.add(
//			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//
//		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN, thruDate));
//	    } else if ("4".equals(dateTypeId)) {
//		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));
//		mainCond0.add(
//			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN, thruDate));
//	    } else if ("5".equals(dateTypeId)) {
//		// 如果存在时间选择
//		if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
//		    mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO,
//			    createTime_fld0_value));
//		}
//		if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
//		    mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN,
//			    createTime_fld1_value));
//		}
//	    }
//
//	    List mainCondUpdateTime = new ArrayList();
//	    if ("1".equals(dateTypeId)) {
//		mainCondUpdateTime.add(
//			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCondUpdateTime.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN, thruDate));
//	    } else if ("2".equals(dateTypeId)) {
//		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));
//		mainCondUpdateTime.add(
//			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCondUpdateTime.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN, thruDate));
//
//	    } else if ("3".equals(dateTypeId)) {
//		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-31));
//		mainCondUpdateTime.add(
//			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//
//		mainCondUpdateTime.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN, thruDate));
//	    } else if ("4".equals(dateTypeId)) {
//		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));
//		mainCondUpdateTime.add(
//			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCondUpdateTime.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN, thruDate));
//	    } else if ("5".equals(dateTypeId)) {
//		// 如果存在时间选择
//		if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
//		    mainCondUpdateTime.add(EntityCondition.makeCondition("updateTime",
//			    EntityOperator.GREATER_THAN_EQUAL_TO, createTime_fld0_value));
//		}
//		if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
//		    mainCondUpdateTime.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN,
//			    createTime_fld1_value));
//		}
//	    }
//	    mainCond0.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
//	    // 新增客户(人)
//	    Long newCrmCustomerNum = delegator.findCountByCondition("CrmCustomer",
//		    EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, null);
//	    // 新增联系人(人)
////			Long newCrmContactsNum = delegator.findCountByCondition("CrmContacts", EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, null);
//	    // 新增商机(个)
//	    Long newCrmBusinessNum = delegator.findCountByCondition("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, null);
//
//
//
//	    List mainCond1 = new ArrayList();
//	    mainCond1.addAll(mainCondUser);
////	    mainCond1.addAll(mainCondUpdateTime);
//
//	    mainCond1.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("5")));
////	    mainCond1.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "5"));
//	    mainCond1.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
//
//	    if ("1".equals(dateTypeId)) {
//		mainCond1.add(
//			EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCond1.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN, thruDate));
//	    } else if ("2".equals(dateTypeId)) {
//		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));
//		mainCond1.add(
//			EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCond1.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN, thruDate));
//
//	    } else if ("3".equals(dateTypeId)) {
//		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-31));
//		mainCond1.add(
//			EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//
//		mainCond1.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN, thruDate));
//	    } else if ("4".equals(dateTypeId)) {
//		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));
//		mainCond1.add(
//			EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCond1.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN, thruDate));
//	    } else if ("5".equals(dateTypeId)) {
//		// 如果存在时间选择
//		if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
//		    mainCond1.add(EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO,
//			    createTime_fld0_value));
//		}
//		if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
//		    mainCond1.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN,
//			    createTime_fld1_value));
//		}
//	    }
//
//	    // 新签合同(个)
//	    Long successCrmBusinessNum = delegator.findCountByCondition("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null, null);
//
//	    List mainCond6 = new ArrayList();
//	    mainCond6.addAll(mainCondUser);
////	    mainCond6.addAll(mainCondUpdateTime);
//	    mainCond6.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "5"));
//	    mainCond6.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
//
//	    if ("1".equals(dateTypeId)) {
//		mainCond6.add(
//			EntityCondition.makeCondition("status6Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCond6.add(EntityCondition.makeCondition("status6Time", EntityOperator.LESS_THAN, thruDate));
//	    } else if ("2".equals(dateTypeId)) {
//		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));
//		mainCond6.add(
//			EntityCondition.makeCondition("status6Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCond6.add(EntityCondition.makeCondition("status6Time", EntityOperator.LESS_THAN, thruDate));
//
//	    } else if ("3".equals(dateTypeId)) {
//		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-31));
//		mainCond6.add(
//			EntityCondition.makeCondition("status6Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//
//		mainCond6.add(EntityCondition.makeCondition("status6Time", EntityOperator.LESS_THAN, thruDate));
//	    } else if ("4".equals(dateTypeId)) {
//		fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));
//		mainCond6.add(
//			EntityCondition.makeCondition("status6Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCond6.add(EntityCondition.makeCondition("status6Time", EntityOperator.LESS_THAN, thruDate));
//	    } else if ("5".equals(dateTypeId)) {
//		// 如果存在时间选择
//		if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
//		    mainCond6.add(EntityCondition.makeCondition("status6Time", EntityOperator.GREATER_THAN_EQUAL_TO,
//			    createTime_fld0_value));
//		}
//		if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
//		    mainCond6.add(EntityCondition.makeCondition("status6Time", EntityOperator.LESS_THAN,
//			    createTime_fld1_value));
//		}
//	    }
//
//	    // 入库商机(个)
//	    Long inWarehouseCrmBusinessNum = delegator.findCountByCondition("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond6, EntityOperator.AND), null, null);
//
//	    List mainCond_chengmo = new ArrayList();
//	    mainCond_chengmo.addAll(mainCondUser);
//	    Timestamp fromDate_chengmo = WvDatetimeUtils.getLastDay(thruDate, new Long(-90));
//	    mainCond_chengmo
//		    .add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN, fromDate_chengmo));
//	    mainCond_chengmo.add(EntityCondition.makeCondition("statusId", EntityOperator.IN,
//		    UtilMisc.toList("0", "1", "2", "3", "4")));
//
//	    List mainCond_chengmo_customer = new ArrayList();
//	    mainCond_chengmo_customer.addAll(mainCondUser);
//	    // Timestamp fromDate_chengmo = WvDatetimeUtils.getLastDay(thruDate, new
//	    // Long(-90));
//	    mainCond_chengmo_customer
//		    .add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN, fromDate_chengmo));
//	    mainCond_chengmo_customer.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
//	    // 沉默客户(人)
//	    Long sixMonthCrmCustomerNum = delegator.findCountByCondition("CrmCustomer",
//		    EntityCondition.makeCondition(mainCond_chengmo_customer, EntityOperator.AND), null, null);
//
//	    List sixMonthCrmCustomerList = delegator.findList("CrmCustomer",
//		    EntityCondition.makeCondition(mainCond_chengmo_customer, EntityOperator.AND), null,
//		    UtilMisc.toList("-createdStamp"), null, true);
//	    mainCond_chengmo.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
//	    // 沉默商机(个数)
//
//	    Long sixMonthCrmBusinessNum = delegator.findCountByCondition("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond_chengmo, EntityOperator.AND), null, null);
//
//	    // 新增合同(个)
////			Long newCrmContractNum = delegator.findCountByCondition("CrmContract", EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, null);
//
//	    List newCrmBusinessList = new ArrayList();
////			List inWarehouseCrmBusinessList=new ArrayList();
//
//	    // 商机金额(元)
//	    Long newCrmBusinessTotalAmount = 0L;
//
//	    //// 商机金额(元)
//	    List<GenericValue> crmBusinessList = delegator.findList("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, UtilMisc.toList("-createTime"),
//		    null, true);
//	    for (GenericValue crmBusiness : crmBusinessList) {
//
//		String businessId = crmBusiness.getString("id");
//		Map param = UtilMisc.toMap("businessId", businessId);
//		List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null, true);
//		BigDecimal totalEstimatedSalesAmount = BigDecimal.ZERO;
//		for (GenericValue crmBusinessItem : crmBusinessItemList) {
//		    if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
//			BigDecimal estimatedSalesAmount = crmBusinessItem.getBigDecimal("estimatedSalesAmount");
//			totalEstimatedSalesAmount = totalEstimatedSalesAmount.add(estimatedSalesAmount);
//		    }
//		}
//		newCrmBusinessTotalAmount = newCrmBusinessTotalAmount + totalEstimatedSalesAmount.longValue();
//
//		Map m = new HashMap();
//		m.putAll(crmBusiness);
//		String customerId = crmBusiness.getString("customerId");
//		if (UtilValidate.isNotEmpty(customerId)) {
//		    GenericValue crmCustomer = delegator.findOne("CrmCustomer", true, UtilMisc.toMap("id", customerId));
//		    if (UtilValidate.isNotEmpty(crmCustomer)) {
//			m.put("customerId_dictText", crmCustomer.getString("customerName"));
//		    }
//		}
//		newCrmBusinessList.add(m);
//	    }
//
//	    // 嬴单商机金额(元)
//	    Long successCrmBusinessTotalAmount = 0L;
//	    List<GenericValue> successCrmBusinessList = delegator.findList("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null, UtilMisc.toList("-createTime"),
//		    null, true);
//	    for (GenericValue successCrmBusiness : successCrmBusinessList) {
//
//		String businessId = successCrmBusiness.getString("id");
//		Map param = UtilMisc.toMap("businessId", businessId);
//		List<GenericValue> successCrmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null,
//			true);
//		BigDecimal successCrmBusiness_totalEstimatedSalesAmount = BigDecimal.ZERO;
//		for (GenericValue successCrmBusinessItem : successCrmBusinessItemList) {
//		    if (UtilValidate.isNotEmpty(successCrmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
//			BigDecimal estimatedSalesAmount = successCrmBusinessItem.getBigDecimal("estimatedSalesAmount");
//			successCrmBusiness_totalEstimatedSalesAmount = successCrmBusiness_totalEstimatedSalesAmount
//				.add(estimatedSalesAmount);
//		    }
//		}
//		successCrmBusinessTotalAmount = successCrmBusinessTotalAmount
//			+ successCrmBusiness_totalEstimatedSalesAmount.longValue();
////				   Map m =new HashMap();
////				   m.putAll(successCrmBusiness);
////				   String customerId =crmBusiness.getString("customerId");
////				   if(UtilValidate.isNotEmpty(customerId)) {
////					   GenericValue  crmCustomer =delegator.findOne("CrmCustomer", true, UtilMisc.toMap("id", customerId));
////					   if(UtilValidate.isNotEmpty(crmCustomer)) {m.put("customerId_dictText",crmCustomer.getString("customerName"));}
////				   }
////				   inWarehouseCrmBusinessList.add(m);
//
//	    }
//
//
//	    //活跃客户   客户如果有成功入仓商机，就始终是活跃的客户。
//	    Long customerCount = 0L;
//
//
//
//	    //沉默客户
//	    //1.1、客户名下无商机，且最近三个月内客户数据无更新；
//	    //1.2、客户名下有商机，客户数据最近三个月内无更新，且最近三个月内该客户名下所有的（非入仓状态的/非失败状态的）商机无更新；
//	    Long businessMoney = 0L;
//
//
//	    List newCrmCustomerList = delegator.findList("CrmCustomer",
//		    EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null,
//		    UtilMisc.toList("-createdStamp"), null, true);
//	    // List newCrmBusinessList = delegator.findList("CrmBusiness",
//	    // EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null,
//	    // UtilMisc.toList("-createdStamp"), null, true);
//
//	    List inWarehouseCrmBusinessList = delegator.findList("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond6, EntityOperator.AND), null,
//		    UtilMisc.toList("-createdStamp"), null, true);
//
//	    List sixMonthCrmBusinessList = delegator.findList("CrmBusiness",
//		    EntityCondition.makeCondition(mainCond_chengmo, EntityOperator.AND), null,
//		    UtilMisc.toList("-createdStamp"), null, true);
//
//	    Map<String, Object> workMap = FastMap.newInstance();
//
//	    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//	    String fromDateDateFormat = simpleDateFormat.format(fromDate);
//	    String thruDateDateFormat = simpleDateFormat.format(thruDate);
//	    if (UtilValidate.isNotEmpty(createTime_fld0_value) && dateTypeId.equals("5")) {
//		workMap.put("fromDate", createTime_fld0_value);
//	    } else {
//		workMap.put("fromDate", fromDateDateFormat);
//	    }
//	    if (UtilValidate.isNotEmpty(createTime_fld1_value) && dateTypeId.equals("5")) {
//		workMap.put("thruDate", createTime_fld1_value);
//	    } else {
//		workMap.put("thruDate", thruDateDateFormat);
//	    }
//
//	    workMap.put("newCrmCustomerNum", newCrmCustomerNum);
//	    workMap.put("newCrmBusinessNum", newCrmBusinessNum);
//	    workMap.put("newCrmBusinessTotalAmount", newCrmBusinessTotalAmount);
//	    workMap.put("successCrmBusinessNum", successCrmBusinessNum);
//	    workMap.put("successCrmBusinessTotalAmount", successCrmBusinessTotalAmount);
//	    workMap.put("inWarehouseCrmBusinessNum", inWarehouseCrmBusinessNum);
//	    workMap.put("sixMonthCrmCustomerNum", sixMonthCrmCustomerNum);
//	    workMap.put("sixMonthCrmBusinessNum", sixMonthCrmBusinessNum);
//
//	    workMap.put("newCrmCustomerList", buildCrmCustomer(delegator, newCrmCustomerList));
//	    workMap.put("newCrmBusinessList", buildCrmBusinessMap(delegator, newCrmBusinessList));
//	    workMap.put("newCrmBusinessTotalAmountList", buildCrmBusinessMap(delegator, newCrmBusinessList));
//	    workMap.put("successCrmBusinessList", buildCrmBusiness(delegator, successCrmBusinessList));
//	    workMap.put("successCrmBusinessTotalAmountList", buildCrmBusiness(delegator, successCrmBusinessList));
//	    workMap.put("inWarehouseCrmBusinessList", buildCrmBusiness(delegator, inWarehouseCrmBusinessList));
//	    workMap.put("sixMonthCrmCustomerList", buildCrmCustomer(delegator, sixMonthCrmCustomerList));
//	    workMap.put("sixMonthCrmBusinessList", buildCrmBusiness(delegator, sixMonthCrmBusinessList));
//
//	    result.put("workMap", workMap);
//
//
//	    LocalDispatcher dispatcher = dctx.getDispatcher();
//
//
//	    Map service_context = new HashMap<>();
//	    service_context.put("objectId", ownerUserId);
//		service_context.put("userLogin", userLogin);
//
//		String personName =getPersonName(delegator, ownerUserId);
//		service_context.put("content", personName +":"+ownerUserId+ "登录记录  ");
//
//		dispatcher.runAsync("createWvVisitLog", service_context);
//
//	} catch (Exception e) {
//	    Debug.logError(e.getMessage(), module);
//	}
//	return result;
//    }

//    private static List buildCrmCustomer(List<GenericValue> inCustomerList) throws GenericEntityException {
//	List result = new ArrayList();
//	Delegator delegator = DelegatorFactory.getDelegator("default");
//	Debug.log("buildCrmCustomer ");
//	for (GenericValue inCustomer : inCustomerList) {
//
//	    // String businessId =inCrmBusiness.getString("id");
//
//	    Map map = new HashMap();
//	    map.putAll(inCustomer);
//	    String ownerUserId = inCustomer.getString("ownerUserId");
//	    if ("public".equals(ownerUserId)) {
//		continue;
//	    }
//	    //Debug.log("buildCrmBusiness ownerUserId= " + ownerUserId);
//	    if (UtilValidate.isNotEmpty(ownerUserId)) {
//
//		GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", ownerUserId),
//			true);
//
//		if (UtilValidate.isNotEmpty(userLogin)) {
//		    GenericValue person = delegator.findOne("Person",
//			    UtilMisc.toMap("partyId", userLogin.getString("partyId")), false);
//		    if (UtilValidate.isNotEmpty(person)) {
//			String ownerUserId_dictText = person.getString("name");
//			map.put("ownerUserId_dictText", ownerUserId_dictText);
//			Debug.log("buildCrmBusiness ownerUserId_dictText= " + ownerUserId_dictText);
//
//		    }
//		}
//
//		List<GenericValue> coRelationshipInfo = delegator.findByAnd("CoRelationship",
//			UtilMisc.toMap("partyIdTo", ownerUserId), null, false);
//		GenericValue coRelationship = EntityUtil.getFirst(coRelationshipInfo);
//
//		if (UtilValidate.isNotEmpty(coRelationship)) {
//		    String partyIdFrom = coRelationship.getString("partyIdFrom");
//
//		    List<GenericValue> dataDictionaryInfo = delegator.findByAnd("DataDictionary",
//			    UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT", "dictionaryCode", partyIdFrom), null,
//			    false);
//		    GenericValue dataDictionary = EntityUtil.getFirst(dataDictionaryInfo);
//		    if (UtilValidate.isNotEmpty(dataDictionary)) {
//			map.put("bu_dictText", dataDictionary.getString("description"));
//		    }
//		}
//
//	    }
//
//	    String contactsId = inCustomer.getString("contactsId");
//	    Debug.log("buildCrmBusiness ownerUserId= " + ownerUserId);
//	    if (UtilValidate.isNotEmpty(contactsId)) {
//		GenericValue crmContacts = delegator.findOne("CrmContacts", UtilMisc.toMap("id", contactsId), true);
//		map.put("contactsId_dictText", crmContacts.getString("name"));
//	    }
//
//	    result.add(map);
//
//	}
//
//	return result;
//    }

    public static List buildCrmBusiness(List inCrmBusinessList) throws GenericEntityException {
	List result = new ArrayList();
	Delegator delegator = DelegatorFactory.getDelegator("default");
//	Debug.log("buildCrmBusiness ");
	for (Object item : inCrmBusinessList) {
	    GenericValue inCrmBusiness = (GenericValue) item;
	    // String businessId =inCrmBusiness.getString("id");

	    Map map = new HashMap();
	    map.putAll(inCrmBusiness);
	    String ownerUserId = inCrmBusiness.getString("ownerUserId");
	    if ("public".equals(ownerUserId)) {
		continue;
	    }
//	    Debug.log("buildCrmBusiness ownerUserId= " + ownerUserId);
	    if (UtilValidate.isNotEmpty(ownerUserId)) {

		GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", ownerUserId),
			true);

		if (UtilValidate.isNotEmpty(userLogin)) {
		    GenericValue person = delegator.findOne("Person",
			    UtilMisc.toMap("partyId", userLogin.getString("partyId")), true);
		    if (UtilValidate.isNotEmpty(person)) {
			String ownerUserId_dictText = person.getString("name");
			map.put("ownerUserId_dictText", ownerUserId_dictText);
//			Debug.log("buildCrmBusiness ownerUserId_dictText= " + ownerUserId_dictText);

		    }
		}
	    }
	    String infoStatusId = (String) inCrmBusiness.get("infoStatusId");
	    if ("1".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "沉默");
	    } else if ("2".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "待激活");
	    } else if ("3".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "活跃");
	    } else if ("4".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "已删除");
	    } else if ("5".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "成功");
	    }

	    String customerId = inCrmBusiness.getString("customerId");
	    if (UtilValidate.isNotEmpty(customerId)) {
		GenericValue crmCustomer = delegator.findOne("CrmCustomer", true, UtilMisc.toMap("id", customerId));
		if (UtilValidate.isNotEmpty(crmCustomer)) {
		    String customerId_dictText = crmCustomer.getString("customerName");
		    map.put("customerId_dictText", customerId_dictText);
		}
	    }

	    String statusId = inCrmBusiness.getString("statusId");
	    if (UtilValidate.isNotEmpty(statusId)) {
		List<GenericValue> dataDictionaryInfo = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryCode", statusId, "dictionaryTypeId", "BUSINESS_STATUS_ID"), null,
			true);
		GenericValue dataDictionary = EntityUtil.getFirst(dataDictionaryInfo);
		if (UtilValidate.isNotEmpty(dataDictionary)) {
		    String statusId_dictText = dataDictionary.getString("description");
		    map.put("statusId_dictText", statusId_dictText);
		}
	    }

	    String businessId = inCrmBusiness.getString("id");
	    Map param = UtilMisc.toMap("businessId", businessId);
	    // param.put("typeId","1");
	    List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null, true);
	    GenericValue crmBusinessItem = EntityUtil.getFirst(crmBusinessItemList);
	    // map.put("crmBusinessItemList",crmBusinessItemList);
	    if (UtilValidate.isNotEmpty(crmBusinessItem)) {
		map.putAll(crmBusinessItem);
		map.put("id", businessId);
		map.put("itemId", crmBusinessItem.getString("id"));
		GenericValue crmWmsInventory = delegator.findOne("CrmWmsInventory", true,
			UtilMisc.toMap("id", crmBusinessItem.getString("inventoryId")));
		if (UtilValidate.isNotEmpty(crmWmsInventory)) {
		    map.put("warehouseName", crmWmsInventory.getString("warehouseName"));
		    map.put("whouseId", crmWmsInventory.getString("id"));

		}
	    }

	    String typeId_dictText = "";
	    Map<String, GenericValue> typeIdMap = new HashMap();

	    List<GenericValue> crmBusinessItemTypeInfo = delegator.findByAnd("CrmBusinessItem",
		    UtilMisc.toMap("businessId", businessId), null, true);
	    for (GenericValue crmBusinessItemType : crmBusinessItemTypeInfo) {
		typeIdMap.put(crmBusinessItemType.getString("typeId"), crmBusinessItemType);
	    }
	    typeIdMap.values();
	    for (String key : typeIdMap.keySet()) {
		if ("1".equals(key)) {
		    typeId_dictText = "仓储";
		}
		if ("2".equals(key)) {
		    if (UtilValidate.isNotEmpty(typeId_dictText)) {
			typeId_dictText += "/";
		    }
		    typeId_dictText += "运输";
		}
		if ("3".equals(key)) {
		    if (UtilValidate.isNotEmpty(typeId_dictText)) {
			typeId_dictText += "/";
		    }
		    typeId_dictText += "货代";
		}
		if ("4".equals(key)) {
		    if (UtilValidate.isNotEmpty(typeId_dictText)) {
			typeId_dictText += "/";
		    }
		    typeId_dictText += "库购";
		}
	    }
	    map.put("typeId_dictText", typeId_dictText);

	    BigDecimal estimatedFreeze = BigDecimal.ZERO;
	    BigDecimal estimatedRefrigerate = BigDecimal.ZERO;
	    BigDecimal estimatedConstant = BigDecimal.ZERO;
	    BigDecimal estimatedNormal = BigDecimal.ZERO;
	    BigDecimal estimatedSalesAmount = BigDecimal.ZERO;
	    for (GenericValue crmBusinessItemType : crmBusinessItemTypeInfo) {
		if (UtilValidate.isNotEmpty(crmBusinessItemType.get("estimatedFreeze"))) {
		    estimatedFreeze = estimatedFreeze.add((BigDecimal) crmBusinessItemType.get("estimatedFreeze"));
		}
		if (UtilValidate.isNotEmpty(crmBusinessItemType.get("estimatedRefrigerate"))) {
		    estimatedRefrigerate = estimatedRefrigerate
			    .add((BigDecimal) crmBusinessItemType.get("estimatedRefrigerate"));
		}
		if (UtilValidate.isNotEmpty(crmBusinessItemType.get("estimatedConstant"))) {
		    estimatedConstant = estimatedConstant
			    .add((BigDecimal) crmBusinessItemType.get("estimatedConstant"));
		}
		if (UtilValidate.isNotEmpty(crmBusinessItemType.get("estimatedNormal"))) {
		    estimatedNormal = estimatedNormal.add((BigDecimal) crmBusinessItemType.get("estimatedNormal"));
		}
		if (UtilValidate.isNotEmpty(crmBusinessItemType.get("estimatedSalesAmount"))) {
		    estimatedSalesAmount = estimatedSalesAmount
			    .add((BigDecimal) crmBusinessItemType.get("estimatedSalesAmount"));
		}

	    }
	    map.put("estimatedFreeze", estimatedFreeze);// 冷冻
	    map.put("estimatedRefrigerate", estimatedRefrigerate);// 冷藏
	    map.put("estimatedConstant", estimatedConstant);// 恒温
	    map.put("estimatedNormal", estimatedNormal);// 常温
	    map.put("estimatedSalesAmount", estimatedSalesAmount);// 预计销售额

	    result.add(map);

	}

	return result;
    }

    private static Map buildCrmBusinessByWhouseId(Delegator delegator, GenericValue inCrmBusiness, String itemId)
	    throws GenericEntityException {

	//Debug.log("buildCrmBusiness inCrmBusiness =" + inCrmBusiness);
	// String businessId =inCrmBusiness.getString("id");
	Map map = new HashMap();
	map.putAll(inCrmBusiness);
	String ownerUserId = inCrmBusiness.getString("ownerUserId");
	if ("public".equals(ownerUserId)) {
	    return map;
	}
	if (UtilValidate.isNotEmpty(ownerUserId)) {
	    GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", ownerUserId), true);
	    if (UtilValidate.isNotEmpty(userLogin)) {
		GenericValue person = delegator.findOne("Person",
			UtilMisc.toMap("partyId", userLogin.getString("partyId")), true);
		if (UtilValidate.isNotEmpty(person)) {
		    String ownerUserId_dictText = person.getString("name");
		    map.put("ownerUserId_dictText", ownerUserId_dictText);
		}
	    }
	}
	String infoStatusId = (String) inCrmBusiness.get("infoStatusId");
	if ("1".equals(infoStatusId)) {
	    map.put("infoStatusId_dictText", "沉默");
	} else if ("2".equals(infoStatusId)) {
	    map.put("infoStatusId_dictText", "待激活");
	} else if ("3".equals(infoStatusId)) {
	    map.put("infoStatusId_dictText", "活跃");
	} else if ("4".equals(infoStatusId)) {
	    map.put("infoStatusId_dictText", "已删除");
	} else if ("5".equals(infoStatusId)) {
	    map.put("infoStatusId_dictText", "成功");
	}

	String customerId = inCrmBusiness.getString("customerId");
	if (UtilValidate.isNotEmpty(customerId)) {
	    GenericValue crmCustomer = delegator.findOne("CrmCustomer", true, UtilMisc.toMap("id", customerId));
	    if (UtilValidate.isNotEmpty(crmCustomer)) {
		String customerId_dictText = crmCustomer.getString("customerName");
		map.put("customerId_dictText", customerId_dictText);
	    }
	}

	String statusId = inCrmBusiness.getString("statusId");
	if (UtilValidate.isNotEmpty(statusId)) {
	    List<GenericValue> dataDictionaryInfo = delegator.findByAnd("DataDictionary",
		    UtilMisc.toMap("dictionaryCode", statusId, "dictionaryTypeId", "BUSINESS_STATUS_ID"), null, true);
	    GenericValue dataDictionary = EntityUtil.getFirst(dataDictionaryInfo);
	    if (UtilValidate.isNotEmpty(dataDictionary)) {
		String statusId_dictText = dataDictionary.getString("description");
		map.put("statusId_dictText", statusId_dictText);
	    }
	}

	String businessId = inCrmBusiness.getString("id");
	GenericValue crmBusinessItem = delegator.findOne("CrmBusinessItem", UtilMisc.toMap("id", itemId), true);
	if (UtilValidate.isNotEmpty(crmBusinessItem)) {
	    if (UtilValidate.isEmpty(crmBusinessItem.get("estimatedFreeze"))) {
		map.put("estimatedFreeze", BigDecimal.ZERO);
	    }
	    if (UtilValidate.isEmpty(crmBusinessItem.get("estimatedRefrigerate"))) {
		map.put("estimatedRefrigerate", BigDecimal.ZERO);
	    }
	    if (UtilValidate.isEmpty(crmBusinessItem.get("estimatedConstant"))) {
		map.put("estimatedConstant", BigDecimal.ZERO);
	    }
	    if (UtilValidate.isEmpty(crmBusinessItem.get("estimatedNormal"))) {
		map.put("estimatedNormal", BigDecimal.ZERO);
	    }
	    if (UtilValidate.isEmpty(crmBusinessItem.get("estimatedSalesAmount"))) {
		map.put("estimatedSalesAmount", BigDecimal.ZERO);
	    }
	    map.putAll(crmBusinessItem);
	    GenericValue crmWmsInventory = delegator.findOne("CrmWmsInventory", true,
		    UtilMisc.toMap("id", crmBusinessItem.getString("inventoryId")));

	    map.put("warehouseName", "_NA_");
	    map.put("whouseId", "_NA_");
	    map.put("warehouseCode", "0");
	    if (UtilValidate.isNotEmpty(crmWmsInventory)) {
		map.put("warehouseName", crmWmsInventory.getString("warehouseName"));
		map.put("whouseId", crmWmsInventory.getString("id"));
		map.put("warehouseCode", crmWmsInventory.getString("warehouseCode"));
	    }

	}
	String typeId_dictText = "";
	Map<String, GenericValue> typeIdMap = new HashMap();

	List<GenericValue> crmBusinessItemTypeInfo = delegator.findByAnd("CrmBusinessItem",
		UtilMisc.toMap("id", itemId), null, true);
	for (GenericValue crmBusinessItemType : crmBusinessItemTypeInfo) {
	    typeIdMap.put(crmBusinessItemType.getString("typeId"), crmBusinessItemType);
	}
	typeIdMap.values();
	for (String key : typeIdMap.keySet()) {
	    if ("1".equals(key)) {
		typeId_dictText = "仓储";
	    }
	    if ("2".equals(key)) {
		if (UtilValidate.isNotEmpty(typeId_dictText)) {
		    typeId_dictText += "/";
		}
		typeId_dictText += "运输";
	    }
	    if ("3".equals(key)) {
		if (UtilValidate.isNotEmpty(typeId_dictText)) {
		    typeId_dictText += "/";
		}
		typeId_dictText += "货代";
	    }
	    if ("4".equals(key)) {
		if (UtilValidate.isNotEmpty(typeId_dictText)) {
		    typeId_dictText += "/";
		}
		typeId_dictText += "库购";
	    }
	}
	map.put("typeId_dictText", typeId_dictText);
	return map;
    }

    private static List buildCrmBusinessMap(Delegator delegator, List<Map> inCrmBusinessList)
	    throws GenericEntityException {
	List result = new ArrayList();

//	Debug.log("buildCrmBusiness");
//	Debug.log("buildCrmBusiness inCrmBusinessList=" + inCrmBusinessList);
	for (Map inCrmBusiness : inCrmBusinessList) {

	    // String businessId =inCrmBusiness.getString("id");

	    Map map = new HashMap();
	    map.putAll(inCrmBusiness);
	    String ownerUserId = (String) inCrmBusiness.get("ownerUserId");
//	    Debug.log("buildCrmBusiness ownerUserId= " + ownerUserId);
	    if ("public".equals(ownerUserId)) {
		continue;
	    }
	    if (UtilValidate.isNotEmpty(ownerUserId)) {

		GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", ownerUserId),
			true);

		if (UtilValidate.isNotEmpty(userLogin)) {
		    GenericValue person = delegator.findOne("Person",
			    UtilMisc.toMap("partyId", userLogin.getString("partyId")), true);
		    if (UtilValidate.isNotEmpty(person)) {
			String ownerUserId_dictText = person.getString("name");
			map.put("ownerUserId_dictText", ownerUserId_dictText);
			Debug.log("buildCrmBusiness ownerUserId_dictText= " + ownerUserId_dictText);

		    }
		}
	    }

	    String infoStatusId = (String) inCrmBusiness.get("infoStatusId");
	    if ("1".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "沉默");
	    } else if ("2".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "待激活");
	    } else if ("3".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "活跃");
	    } else if ("4".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "已删除");
	    } else if ("5".equals(infoStatusId)) {
		map.put("infoStatusId_dictText", "成功");
	    }

	    String customerId = (String) inCrmBusiness.get("customerId");
	    if (UtilValidate.isNotEmpty(customerId)) {
		GenericValue crmCustomer = delegator.findOne("CrmCustomer", true, UtilMisc.toMap("id", customerId));
		if (UtilValidate.isNotEmpty(crmCustomer)) {
		    String customerId_dictText = crmCustomer.getString("customerName");
		    map.put("customerId_dictText", customerId_dictText);
		}
	    }

	    String statusId = (String) inCrmBusiness.get("statusId");
	    if (UtilValidate.isNotEmpty(statusId)) {
		List<GenericValue> dataDictionaryInfo = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryCode", statusId, "dictionaryTypeId", "BUSINESS_STATUS_ID"), null,
			true);
		GenericValue dataDictionary = EntityUtil.getFirst(dataDictionaryInfo);
		if (UtilValidate.isNotEmpty(dataDictionary)) {
		    String statusId_dictText = dataDictionary.getString("description");
		    map.put("statusId_dictText", statusId_dictText);
		}
	    }

	    String businessId = (String) inCrmBusiness.get("id");
	    Map param = UtilMisc.toMap("businessId", businessId);
	    param.put("typeId", "1");
	    List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null, true);
	    GenericValue crmBusinessItem = EntityUtil.getFirst(crmBusinessItemList);
	    // map.put("crmBusinessItemList",crmBusinessItemList);
	    if (UtilValidate.isNotEmpty(crmBusinessItem)) {
		map.putAll(crmBusinessItem);
		GenericValue crmWmsInventory = delegator.findOne("CrmWmsInventory", true,
			UtilMisc.toMap("id", crmBusinessItem.getString("inventoryId")));
		if (UtilValidate.isNotEmpty(crmWmsInventory)) {
		    map.put("warehouseName", crmWmsInventory.getString("warehouseName"));
		}

	    }
//			    if(UtilValidate.isEmpty(map.get("typeId"))) {
//			    	List<GenericValue> crmBusinessItemInfo = delegator.findByAnd("CrmBusinessItem",UtilMisc.toMap("businessId", businessId) ,null, true);
//			    	GenericValue crmBusinessItemFirst =EntityUtil.getFirst(crmBusinessItemInfo);
//			    	 if(UtilValidate.isNotEmpty(crmBusinessItemFirst)) {
//			    		 map.put("typeId",crmBusinessItemFirst.getString("typeId"));
//			    	 }
//
//			    }
	    String typeId_dictText = "";
	    Map<String, GenericValue> typeIdMap = new HashMap();

	    List<GenericValue> crmBusinessItemTypeInfo = delegator.findByAnd("CrmBusinessItem",
		    UtilMisc.toMap("businessId", businessId), null, true);
	    for (GenericValue crmBusinessItemType : crmBusinessItemTypeInfo) {
		typeIdMap.put(crmBusinessItemType.getString("typeId"), crmBusinessItemType);
	    }
	    typeIdMap.values();
	    for (String key : typeIdMap.keySet()) {
		if ("1".equals(key)) {
		    typeId_dictText = "仓储";
		}
		if ("2".equals(key)) {
		    if (UtilValidate.isNotEmpty(typeId_dictText)) {
			typeId_dictText += "/";
		    }
		    typeId_dictText += "运输";
		}
		if ("3".equals(key)) {
		    if (UtilValidate.isNotEmpty(typeId_dictText)) {
			typeId_dictText += "/";
		    }
		    typeId_dictText += "货代";
		}
		if ("4".equals(key)) {
		    if (UtilValidate.isNotEmpty(typeId_dictText)) {
			typeId_dictText += "/";
		    }
		    typeId_dictText += "库购";
		}
	    }
	    map.put("typeId_dictText", typeId_dictText);

	    BigDecimal estimatedFreeze = BigDecimal.ZERO;
	    BigDecimal estimatedRefrigerate = BigDecimal.ZERO;
	    BigDecimal estimatedConstant = BigDecimal.ZERO;
	    BigDecimal estimatedNormal = BigDecimal.ZERO;
	    BigDecimal estimatedSalesAmount = BigDecimal.ZERO;
	    for (GenericValue crmBusinessItemType : crmBusinessItemTypeInfo) {
		if (UtilValidate.isNotEmpty(crmBusinessItemType.get("estimatedFreeze"))) {
		    estimatedFreeze = estimatedFreeze.add((BigDecimal) crmBusinessItemType.get("estimatedFreeze"));
		}
		if (UtilValidate.isNotEmpty(crmBusinessItemType.get("estimatedRefrigerate"))) {
		    estimatedRefrigerate = estimatedRefrigerate
			    .add((BigDecimal) crmBusinessItemType.get("estimatedRefrigerate"));
		}
		if (UtilValidate.isNotEmpty(crmBusinessItemType.get("estimatedConstant"))) {
		    estimatedConstant = estimatedConstant
			    .add((BigDecimal) crmBusinessItemType.get("estimatedConstant"));
		}
		if (UtilValidate.isNotEmpty(crmBusinessItemType.get("estimatedNormal"))) {
		    estimatedNormal = estimatedNormal.add((BigDecimal) crmBusinessItemType.get("estimatedNormal"));
		}
		if (UtilValidate.isNotEmpty(crmBusinessItemType.get("estimatedSalesAmount"))) {
		    estimatedSalesAmount = estimatedSalesAmount
			    .add((BigDecimal) crmBusinessItemType.get("estimatedSalesAmount"));
		}

	    }
	    map.put("estimatedFreeze", estimatedFreeze);// 冷冻
	    map.put("estimatedRefrigerate", estimatedRefrigerate);// 冷藏
	    map.put("estimatedConstant", estimatedConstant);// 恒温
	    map.put("estimatedNormal", estimatedNormal);// 常温
	    map.put("estimatedSalesAmount", estimatedSalesAmount);// 预计销售额

	    result.add(map);

	}

	return result;
    }

    /**
     * 销售报告
     */
    public static Map<String, Object> getSalesDataTotalAnalysis(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Debug.log("getSalesDataTotalAnalysis == start");
	String ownerUserId = userLogin.getString("userLoginId");
//		String isExternal = (String) context.get("isExternal");

	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));

	// 所属bu
	String onlyBu = (String) context.get("onlyBu");
	List<String> baseIdList = new ArrayList();
	try {
	    if ("Y".equals(onlyBu)) {

		List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdTo", ownerUserId, "statusId", "PARTY_ENABLED", "partyRelationshipTypeId",
				"COMPANY_EMPLOYEE"),
			null, true);
		if (UtilValidate.isNotEmpty(coRelationshipList)) {
		    for (int i = 0; i < coRelationshipList.size(); i++) {
			GenericValue coRelationship = coRelationshipList.get(i);
			String partyIdFrom = coRelationship.getString("partyIdFrom");
			baseIdList.add(partyIdFrom);
		    }
		}

	    }

	    EntityCondition mainCond = null;
	    List<EntityCondition> andExprs = FastList.newInstance();
	    if (UtilValidate.isNotEmpty(baseIdList)) {
		andExprs.add(EntityCondition.makeCondition("ownerBuId", EntityOperator.IN, baseIdList));
	    }
	    andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "Y"));
	    andExprs.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    if (andExprs.size() > 0) {
		mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);
	    }

	    // 按仓库统计 销售情况
	    List salesDataListByWarehouse = new ArrayList();

	    // 销售预警
	    List cautionSalesDataListByWarehouse = new ArrayList();

	    List orderBy = UtilMisc.toList("warehouseCode");
	    List<GenericValue> entityList = delegator.findList("CrmWmsInventory", mainCond, null, orderBy, null, true);

	    for (GenericValue entity : entityList) {
		Map<String, Object> map = FastMap.newInstance();
		Map<String, Object> cautionSalesDataMap = FastMap.newInstance();

		String id = entity.getString("id");
		// String ownerBuId = entity.getString("ownerBuId");
		String warehouseName = entity.getString("warehouseName");
		// 建设冷冻容量
		BigDecimal buildingFreeze = entity.getBigDecimal("buildingFreeze");
		buildingFreeze = UtilValidate.isEmpty(buildingFreeze) ? BigDecimal.ZERO : buildingFreeze;
		// 已使用冷冻
		BigDecimal physicalFreeze = entity.getBigDecimal("physicalFreeze");
		physicalFreeze = UtilValidate.isEmpty(physicalFreeze) ? BigDecimal.ZERO : physicalFreeze;
		// 剩余量
		BigDecimal availableFreeze = buildingFreeze.subtract(physicalFreeze);

		// 建设冷藏容量
		BigDecimal buildingRefrigerate = entity.getBigDecimal("buildingRefrigerate");
		buildingRefrigerate = UtilValidate.isEmpty(buildingRefrigerate) ? BigDecimal.ZERO : buildingRefrigerate;
		// 已使用冷藏
		BigDecimal physicalRefrigerate = entity.getBigDecimal("physicalRefrigerate");
		physicalRefrigerate = UtilValidate.isEmpty(physicalRefrigerate) ? BigDecimal.ZERO : physicalRefrigerate;
		BigDecimal availableRefrigerate = buildingRefrigerate.subtract(physicalRefrigerate);

		// 建设恒温容量
		BigDecimal buildingConstant = entity.getBigDecimal("buildingConstant");
		buildingConstant = UtilValidate.isEmpty(buildingConstant) ? BigDecimal.ZERO : buildingConstant;
		// 已使用恒温
		BigDecimal physicalConstant = entity.getBigDecimal("physicalConstant");
		physicalConstant = UtilValidate.isEmpty(physicalConstant) ? BigDecimal.ZERO : physicalConstant;
		BigDecimal availableConstant = buildingConstant.subtract(physicalConstant);

		// 建设常温容量
		BigDecimal buildingNormal = entity.getBigDecimal("buildingNormal");
		buildingNormal = UtilValidate.isEmpty(buildingNormal) ? BigDecimal.ZERO : buildingNormal;
		// 已使用常温
		BigDecimal physicalNormal = entity.getBigDecimal("physicalNormal");
		physicalNormal = UtilValidate.isEmpty(physicalNormal) ? BigDecimal.ZERO : physicalNormal;
		BigDecimal availableNormal = buildingNormal.subtract(physicalNormal);
		// 已用库存小计
		BigDecimal physicalTotal = physicalFreeze.add(physicalRefrigerate).add(physicalConstant)
			.add(physicalNormal);

		// 可用库存小计
		BigDecimal availableTotal = availableFreeze.add(availableRefrigerate).add(availableConstant)
			.add(availableNormal);

		Map estimatedInventory = getSaleInventory(delegator, id);
		BigDecimal estimatedFreeze = (BigDecimal) estimatedInventory.get("estimatedFreeze");
		BigDecimal estimatedRefrigerate = (BigDecimal) estimatedInventory.get("estimatedRefrigerate");
		BigDecimal estimatedConstant = (BigDecimal) estimatedInventory.get("estimatedConstant");
		BigDecimal estimatedNormal = (BigDecimal) estimatedInventory.get("estimatedNormal");
		// 预测销售库存小计;
		BigDecimal estimatedTotal = estimatedFreeze.add(estimatedRefrigerate).add(estimatedConstant)
			.add(estimatedNormal);
		// 销售库位与空余库位占比
		// BigDecimal estimatedDivAvailableRate = estimatedTotal.divide(availableTotal,
		// 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
		BigDecimal availableFreezeDivide = availableFreeze;
		BigDecimal availableRefrigerateDivide = availableRefrigerate;
		BigDecimal availableConstantDivide = availableConstant;
		BigDecimal availableNormalDivide = availableNormal;
		BigDecimal availableTotalDivide = availableTotal;
		BigDecimal estimatedTotalDivide = estimatedTotal;

		if (availableFreezeDivide.compareTo(BigDecimal.ONE) < 0) {
		    availableFreezeDivide = BigDecimal.ONE;
		}
		if (availableRefrigerateDivide.compareTo(BigDecimal.ONE) < 0) {
		    availableRefrigerateDivide = BigDecimal.ONE;
		}
		if (availableConstantDivide.compareTo(BigDecimal.ONE) < 0) {
		    availableConstantDivide = BigDecimal.ONE;
		}
		if (availableNormalDivide.compareTo(BigDecimal.ONE) < 0) {
		    availableNormalDivide = BigDecimal.ONE;
		}
		if (availableTotalDivide.compareTo(BigDecimal.ONE) < 0) {
		    availableTotalDivide = BigDecimal.ONE;
		}
		if (estimatedTotalDivide.compareTo(BigDecimal.ONE) < 0) {
		    estimatedTotalDivide = BigDecimal.ONE;
		}

		// 冷冻销售库位与空余库位占比
		BigDecimal estimatedFreezeRate = estimatedFreeze
			.divide(availableFreezeDivide, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
		// 冷藏销售库位与空余库位占比
		BigDecimal estimatedRefrigerateRate = estimatedRefrigerate
			.divide(availableRefrigerateDivide, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
		// 恒温销售库位与空余库位占比
		BigDecimal estimatedConstantRate = estimatedConstant
			.divide(availableConstantDivide, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
		// 常温销售库位与空余库位占比
		BigDecimal estimatedNormalRate = estimatedNormal
			.divide(availableNormalDivide, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));

		// 总计销售库位与总计空余库位占比
		BigDecimal estimatedTotalRate = estimatedTotal.divide(availableTotalDivide, 2, BigDecimal.ROUND_HALF_UP)
			.multiply(new BigDecimal(100));

		// 总计空余库位与总计销售库位占比
		BigDecimal estimatedTotalRate2 = availableTotalDivide
			.divide(estimatedTotalDivide, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));

		map.put("warehouseName", warehouseName);
		// map.put("estimatedDivAvailableRate", estimatedDivAvailableRate);
		// 已使用
		map.put("physicalFreeze", physicalFreeze);
		map.put("physicalRefrigerate", physicalRefrigerate);
		map.put("physicalConstant", physicalConstant);
		map.put("physicalNormal", physicalNormal);
		map.put("physicalTotal", physicalTotal);

		map.put("availableFreeze", availableFreeze);
		map.put("estimatedFreeze", estimatedFreeze);
		map.put("estimatedFreezeRate", estimatedFreezeRate);

		map.put("availableRefrigerate", availableRefrigerate);
		map.put("estimatedRefrigerate", estimatedRefrigerate);
		map.put("estimatedRefrigerateRate", estimatedRefrigerateRate);

		map.put("availableConstant", availableConstant);
		map.put("estimatedConstant", estimatedConstant);
		map.put("estimatedConstantRate", estimatedConstantRate);

		map.put("availableNormal", availableNormal);
		map.put("estimatedNormal", estimatedNormal);
		map.put("estimatedNormalRate", estimatedNormalRate);

		map.put("availableTotal", availableTotal);
		map.put("estimatedTotal", estimatedTotal);
		map.put("estimatedTotalRate", estimatedTotalRate);

		map.put("estimatedTotalRate2", estimatedTotalRate2);

		salesDataListByWarehouse.add(map);

		cautionSalesDataMap.put("warehouseName", warehouseName);

		// 已使用
		cautionSalesDataMap.put("physicalFreeze", physicalFreeze);
		cautionSalesDataMap.put("physicalRefrigerate", physicalRefrigerate);
		cautionSalesDataMap.put("physicalConstant", physicalConstant);
		cautionSalesDataMap.put("physicalNormal", physicalNormal);
		cautionSalesDataMap.put("physicalTotal", physicalTotal);

		boolean estimatedFreezeRateDisplay = false;
		boolean estimatedRefrigerateRateDisplay = false;
		boolean estimatedConstantRateDisplay = false;
		boolean estimatedNormalRateDisplay = false;

		if (lessThan(estimatedFreezeRate, new BigDecimal(120))
			&& greaterThan(buildingFreeze, BigDecimal.ZERO)) {
		    estimatedFreezeRateDisplay = true;
		}
		if (lessThan(estimatedRefrigerateRate, new BigDecimal(120))
			&& greaterThan(buildingRefrigerate, BigDecimal.ZERO)) {
		    estimatedRefrigerateRateDisplay = true;
		}
		if (lessThan(estimatedConstantRate, new BigDecimal(120))
			&& greaterThan(buildingConstant, BigDecimal.ZERO)) {
		    estimatedConstantRateDisplay = true;
		}
		if (lessThan(estimatedNormalRate, new BigDecimal(120))
			&& greaterThan(buildingNormal, BigDecimal.ZERO)) {
		    estimatedNormalRateDisplay = true;
		}

		if (estimatedFreezeRateDisplay) {
		    cautionSalesDataMap.put("availableFreeze", availableFreeze);
		    cautionSalesDataMap.put("estimatedFreeze", estimatedFreeze);
		    cautionSalesDataMap.put("estimatedFreezeRate", estimatedFreezeRate);
		    cautionSalesDataMap.put("estimatedFreezeRateNo", new BigDecimal(120).subtract(estimatedFreezeRate));

		    if (estimatedFreezeRate.compareTo(new BigDecimal(100)) < 0) {
			cautionSalesDataMap.put("estimatedFreezeRate100",
				new BigDecimal(120).subtract(estimatedFreezeRate));
		    }
		    if (estimatedFreezeRate.compareTo(new BigDecimal(100)) > 0) {
			cautionSalesDataMap.put("estimatedFreezeRate200",
				new BigDecimal(120).subtract(estimatedFreezeRate));
		    }
		}

		if (estimatedRefrigerateRateDisplay) {
		    cautionSalesDataMap.put("availableRefrigerate", availableRefrigerate);
		    cautionSalesDataMap.put("estimatedRefrigerate", estimatedRefrigerate);
		    cautionSalesDataMap.put("estimatedRefrigerateRate", estimatedRefrigerateRate);
		    cautionSalesDataMap.put("estimatedRefrigerateRateNo",
			    new BigDecimal(120).subtract(estimatedRefrigerateRate));

		    if (estimatedRefrigerateRate.compareTo(new BigDecimal(100)) < 0) {
			cautionSalesDataMap.put("estimatedRefrigerateRate100",
				new BigDecimal(120).subtract(estimatedRefrigerateRate));
		    }
		    if (estimatedRefrigerateRate.compareTo(new BigDecimal(100)) > 0) {
			cautionSalesDataMap.put("estimatedRefrigerateRate200",
				new BigDecimal(120).subtract(estimatedRefrigerateRate));
		    }
		}
		if (estimatedConstantRateDisplay) {
		    cautionSalesDataMap.put("availableConstant", availableConstant);
		    cautionSalesDataMap.put("estimatedConstant", estimatedConstant);
		    cautionSalesDataMap.put("estimatedConstantRate", estimatedConstantRate);
		    cautionSalesDataMap.put("estimatedConstantRateNo",
			    new BigDecimal(120).subtract(estimatedConstantRate));

		    if (estimatedConstantRate.compareTo(new BigDecimal(100)) < 0) {
			cautionSalesDataMap.put("estimatedConstantRate100",
				new BigDecimal(120).subtract(estimatedConstantRate));
		    }
		    if (estimatedConstantRate.compareTo(new BigDecimal(100)) > 0) {
			cautionSalesDataMap.put("estimatedConstantRate200",
				new BigDecimal(120).subtract(estimatedConstantRate));
		    }
		}
		if (estimatedNormalRateDisplay) {
		    cautionSalesDataMap.put("availableNormal", availableNormal);
		    cautionSalesDataMap.put("estimatedNormal", estimatedNormal);
		    cautionSalesDataMap.put("estimatedNormalRate", estimatedNormalRate);
		    cautionSalesDataMap.put("estimatedNormalRateNo", new BigDecimal(120).subtract(estimatedNormalRate));

		    if (estimatedNormalRate.compareTo(new BigDecimal(100)) < 0) {
			cautionSalesDataMap.put("estimatedNormalRate100",
				new BigDecimal(120).subtract(estimatedNormalRate));
		    }
		    if (estimatedNormalRate.compareTo(new BigDecimal(100)) > 0) {
			cautionSalesDataMap.put("estimatedNormalRate200",
				new BigDecimal(120).subtract(estimatedNormalRate));
		    }
		}

		if (estimatedFreezeRateDisplay || estimatedRefrigerateRateDisplay || estimatedConstantRateDisplay
			|| estimatedNormalRateDisplay) {
		    cautionSalesDataListByWarehouse.add(cautionSalesDataMap);
		}
	    }

	    Map<String, Object> workMap = FastMap.newInstance();

	    workMap.put("customerListByProductCategory", customerListByProductCategory(delegator, onlyBu, ownerUserId));
	    // workMap.put("businessListByProductCategory",
	    // businessListByProductCategory(delegator,"month"));

	    workMap.put("salesDataListByWarehouse", salesDataListByWarehouse);
	    workMap.put("cautionSalesDataListByWarehouse", cautionSalesDataListByWarehouse);

	    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    String fromDateDateFormat = simpleDateFormat.format(fromDate);
	    String thruDateDateFormat = simpleDateFormat.format(thruDate);
	    workMap.put("fromDate", fromDateDateFormat);
	    workMap.put("thruDate", thruDateDateFormat);

	    result.put("workMap", workMap);
	    Debug.log("getSalesDataTotalAnalysis == end");
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    /**
     * 外仓销售报告
     */
    public static Map<String, Object> getOutsideWmsReport(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Debug.log("getOutsideWmsReport == start");

	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));

	try {

	    List<EntityCondition> andExprs = FastList.newInstance();

	    andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.IN,
		    UtilMisc.toList("0", "1", "2", "3", "4", "5")));

	    andExprs.add(EntityCondition.makeCondition("inventoryId", EntityOperator.EQUALS, "6666"));
	    andExprs.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "1"));

	    EntityCondition mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);

	    // 按仓库统计 销售情况
	    // List salesDataListByWarehouse = new ArrayList();

	    // 销售预警
//			List cautionSalesDataListByWarehouse = new ArrayList();

	    List orderBy = UtilMisc.toList("outerWarehouse");
	    List<GenericValue> entityList = delegator.findList("CrmBusinessItemByTypeId", mainCond, null, orderBy, null,
		    true);

	    Map outerWarehouseMap = new HashMap();

	    for (GenericValue entity : entityList) {

		BigDecimal followup = BigDecimal.ONE;
		if (UtilValidate.isNotEmpty(entity.get("followup"))) {
		    followup = new BigDecimal(entity.getString("followup"));
		}
		String warehouseName = entity.getString("outerWarehouse");

		BigDecimal estimatedFreeze = BigDecimal.ZERO;
		BigDecimal estimatedRefrigerate = BigDecimal.ZERO;
		BigDecimal estimatedConstant = BigDecimal.ZERO;
		BigDecimal estimatedNormal = BigDecimal.ZERO;

		if (UtilValidate.isNotEmpty(entity.get("estimatedFreeze"))) {
		    estimatedFreeze = (BigDecimal) entity.get("estimatedFreeze");
		    estimatedFreeze = estimatedFreeze.multiply(followup).divide(new BigDecimal(100));
		}
		if (UtilValidate.isNotEmpty(entity.get("estimatedRefrigerate"))) {
		    estimatedRefrigerate = (BigDecimal) entity.get("estimatedRefrigerate");
		    estimatedRefrigerate = estimatedRefrigerate.multiply(followup).divide(new BigDecimal(100));
		}
		if (UtilValidate.isNotEmpty(entity.get("estimatedConstant"))) {
		    estimatedConstant = (BigDecimal) entity.get("estimatedConstant");
		    estimatedConstant = estimatedConstant.multiply(followup).divide(new BigDecimal(100));
		}
		if (UtilValidate.isNotEmpty(entity.get("estimatedNormal"))) {
		    estimatedNormal = (BigDecimal) entity.get("estimatedNormal");
		    estimatedNormal = estimatedNormal.multiply(followup).divide(new BigDecimal(100));
		}

		// 预测销售库存小计;
		BigDecimal estimatedTotal = estimatedFreeze.add(estimatedRefrigerate).add(estimatedConstant)
			.add(estimatedNormal);

//				estimatedTotal =estimatedTotal.multiply(followup).divide(new BigDecimal(100));

		if (UtilValidate.isEmpty(outerWarehouseMap.get(warehouseName))) {
		    Map collectData = new HashMap();

		    collectData.put("warehouseName", warehouseName);
		    collectData.put("estimatedFreeze", estimatedFreeze);
		    collectData.put("estimatedRefrigerate", estimatedRefrigerate);
		    collectData.put("estimatedConstant", estimatedConstant);
		    collectData.put("estimatedNormal", estimatedNormal);
		    collectData.put("estimatedTotal", estimatedTotal);

		    outerWarehouseMap.put(warehouseName, collectData);
		} else {
		    Map collectData = new HashMap();
		    Map oldCollectData = (Map) outerWarehouseMap.get(warehouseName);
		    collectData.putAll(oldCollectData);
		    BigDecimal newEstimatedFreeze = estimatedFreeze
			    .add((BigDecimal) oldCollectData.get("estimatedFreeze"));
		    Debug.log("newEstimatedFreeze = " + newEstimatedFreeze);
		    collectData.put("estimatedFreeze", newEstimatedFreeze);

		    BigDecimal newEstimatedRefrigerate = estimatedRefrigerate
			    .add((BigDecimal) oldCollectData.get("estimatedRefrigerate"));
		    Debug.log("newEstimatedRefrigerate = " + newEstimatedRefrigerate);
		    collectData.put("estimatedRefrigerate", newEstimatedRefrigerate);

		    BigDecimal newEstimatedConstant = estimatedConstant
			    .add((BigDecimal) oldCollectData.get("estimatedConstant"));
		    Debug.log("newEstimatedConstant = " + newEstimatedConstant);
		    collectData.put("estimatedConstant", newEstimatedConstant);

		    BigDecimal newEstimatedNormal = estimatedNormal
			    .add((BigDecimal) oldCollectData.get("estimatedNormal"));
		    Debug.log("newEstimatedNormal = " + newEstimatedNormal);
		    collectData.put("estimatedNormal", newEstimatedNormal);

		    BigDecimal newEstimatedTotal = estimatedTotal
			    .add((BigDecimal) oldCollectData.get("estimatedTotal"));
		    Debug.log("newEstimatedTotal = " + newEstimatedTotal);
		    collectData.put("estimatedTotal", newEstimatedTotal);

		    outerWarehouseMap.put(warehouseName, collectData);

		}

		// map.put("warehouseName", warehouseName);

	    }

	    Map<String, Object> workMap = FastMap.newInstance();

	    workMap.put("salesDataListByWarehouse", new ArrayList(outerWarehouseMap.values()));

	    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    String fromDateDateFormat = simpleDateFormat.format(fromDate);
	    String thruDateDateFormat = simpleDateFormat.format(thruDate);
	    workMap.put("fromDate", fromDateDateFormat);
	    workMap.put("thruDate", thruDateDateFormat);

	    result.put("workMap", workMap);
	    Debug.log("getOutsideWmsReport == end");
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    private static List customerListByProductCategory(Delegator delegator, String onlyBu, String ownerUserId) {
	List result = new ArrayList();
	try {

	    ArrayList<EntityCondition> mainCond = new ArrayList<>();
	    List<String> baseIdList = new ArrayList();

	    if ("Y".equals(onlyBu)) {

		List<GenericValue> coRelationshipInfo = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdTo", ownerUserId, "statusId", "PARTY_ENABLED", "partyRelationshipTypeId",
				"COMPANY_EMPLOYEE"),
			null, true);
		if (UtilValidate.isNotEmpty(coRelationshipInfo)) {

		    GenericValue coRelationshipFrom = EntityUtil.getFirst(coRelationshipInfo);
		    if (UtilValidate.isNotEmpty(coRelationshipInfo)) {
			String partyIdFrom = coRelationshipFrom.getString("partyIdFrom");
			List<GenericValue> coRelationshipList = delegator
				.findByAnd(
					"CoRelationship", UtilMisc.toMap("partyIdFrom", partyIdFrom, "statusId",
						"PARTY_ENABLED", "partyRelationshipTypeId", "COMPANY_EMPLOYEE"),
					null, true);
			for (int i = 0; i < coRelationshipList.size(); i++) {
			    GenericValue coRelationship = coRelationshipList.get(i);
			    String partyIdTo = coRelationship.getString("partyIdTo");
			    baseIdList.add(partyIdTo);
			}
		    }

		}

		mainCond.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, baseIdList));
	    } else {
		mainCond.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.NOT_EQUAL, "public"));
	    }
	    mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	    List<GenericValue> crmCustomerList;

	    crmCustomerList = delegator.findList("CrmCustomerAndDy",
		    EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, UtilMisc.toList("sequenceId"),
		    null, true);

	    Map map = new HashMap();
	    for (GenericValue crmCustomer : crmCustomerList) {
		String productCategory = crmCustomer.getString("productCategory");
		if (UtilValidate.isEmpty(productCategory)) {
		    continue;
		}
		if (UtilValidate.isEmpty(map.get(productCategory))) {
		    Map productCategoryData = new HashMap();
		    GenericValue gv = delegator.findOne("DataDictionary", true,
			    UtilMisc.toMap("dictionaryId", productCategory));

		    productCategoryData.put("productCategoryName", gv.getString("description"));
		    productCategoryData.put("productCategory", productCategory);
		    productCategoryData.put("sequenceId", gv.getString("sequenceId"));
		    int customerNum = 1;
		    productCategoryData.put("customerNum", customerNum);

		    map.put(productCategory, productCategoryData);
		} else {
		    Map productCategoryData = new HashMap();
		    Map oldProductCategoryData = (Map) map.get(productCategory);
		    // Debug.log("oldPersonData = "+oldPersonData);
		    productCategoryData.putAll(oldProductCategoryData);
		    // Debug.log("oldPersonData.get(businessNum) =
		    // "+oldPersonData.get("businessNum"));
		    int customerNum = (int) oldProductCategoryData.get("customerNum") + 1;
		    Debug.log("customerNum = " + customerNum);
		    productCategoryData.put("customerNum", customerNum);

		    map.put(productCategory, productCategoryData);

		}
	    }
	    Debug.log("customerListByProductCategory map =" + map);
	    List mapList = new ArrayList(map.values());
	    Map t = (Map) map.get("PRODUCT_CATEGORY19");
	    map.remove("PRODUCT_CATEGORY19");
	    Collections.sort(mapList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = ((String) obj1.get("sequenceId")).compareTo((String) obj2.get("sequenceId"));
		    return i;
		}
	    });
	    mapList.add(t);
	    result = mapList;
	} catch (GenericEntityException e) {
	    Debug.log(e.getMessage(), "customerListByProductCategory");
	}
	Debug.log("customerListByProductCategory result =" + result);
	return result;
    }

    public static String getBu(Delegator delegator, String userLoginId, String isArea) throws GenericEntityException {
	String id = "";
	List<GenericValue> itemShipList = delegator.findByAnd("CoRelationship",
		UtilMisc.toMap("partyIdTo", userLoginId), null, true);

	if (UtilValidate.isNotEmpty(itemShipList)) {
	    String buCode = EntityUtil.getFirst(itemShipList).getString("partyIdFrom");
	    List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
		    UtilMisc.toMap("dictionaryCode", buCode), UtilMisc.toList("sequenceId"), true);
	    GenericValue data = EntityUtil.getFirst(dataList);
	    if (isArea.equals("N")) {
		id = buCode;
	    } else {
		String areaId = data.getString("parentId");
		if (UtilValidate.isNotEmpty(areaId)) {
		    GenericValue areaData = delegator.findOne("DataDictionary", true,
			    UtilMisc.toMap("dictionaryId", areaId));
		    String dictionaryCode11 = areaData.getString("dictionaryCode");
		    id = dictionaryCode11;
		}
	    }
	}
	return id;
    }

    // 商机报告2.0
    public static Map<String, Object> getNewSalesDataTotalAnalysis(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Debug.log("getNewSalesDataTotalAnalysis1 == start");
	String ownerUserId = userLogin.getString("userLoginId");

	String notFollowup = "N";

	if (UtilValidate.isNotEmpty(context.get("notFollowup"))) {
	    notFollowup = (String) context.get("notFollowup");
	}

	// 所属bu
	List<String> baseIdList = new ArrayList();
	try {
	    String personTypeId = (String) context.get("personTypeId");
	    Timestamp createTime_fld0_value = (Timestamp) context.get("createTime_fld0_value");
	    Timestamp createTime_fld1_value = (Timestamp) context.get("createTime_fld1_value");
	    if (UtilValidate.isEmpty(createTime_fld0_value)) {
		createTime_fld0_value = CommonUtils.getLastYear(-2);
	    }
	    if (UtilValidate.isEmpty(createTime_fld1_value)) {
		createTime_fld1_value = UtilDateTime.nowTimestamp();
	    }
	    List ownerUserIdList = new ArrayList();
	    if (UtilValidate.isEmpty(personTypeId)) {
		personTypeId = "2";
	    }
	    if ("2".equals(personTypeId)) {// 本bu
		String buCode = getBu(delegator, ownerUserId, "N");
		baseIdList.add(buCode);
	    } else if ("allData".equals(personTypeId)) { // 全国
		List<GenericValue> buList = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT"), UtilMisc.toList("sequenceId"), true);
		x: for (GenericValue bu : buList) {
		    String dictionaryCode2 = bu.getString("dictionaryCode2");
		    if ("N".equals(dictionaryCode2)) {
			continue x;
		    }
		    baseIdList.add(bu.getString("dictionaryCode"));
		}

	    } else if ("3".equals(personTypeId)) { // 本大区
		// 先找到人属于那个bu.找到bu属于哪个大区.
		List<GenericValue> shipList = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdTo", ownerUserId), null, false);
		if (UtilValidate.isNotEmpty(shipList)) {
		    // 获取buCode
		    String buCode = EntityUtil.getFirst(shipList).getString("partyIdFrom");
		    List<GenericValue> dataList1 = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("dictionaryCode", buCode), null, false);

		    GenericValue data1 = EntityUtil.getFirst(dataList1);
		    String areaId = data1.getString("parentId");
		    // 获取大区ID
		    if (UtilValidate.isNotEmpty(areaId)) {
			// 获取大区下的bu列表
			List<GenericValue> sunBuList = delegator.findByAnd("DataDictionary",
				UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT", "parentId", areaId), null, true);
			x: for (GenericValue bu : sunBuList) {
			    String dictionaryCode2 = bu.getString("dictionaryCode2");
			    if ("N".equals(dictionaryCode2)) {
				continue x;
			    }
			    baseIdList.add(bu.getString("dictionaryCode"));
			}
		    }

		}
	    } else {
		List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryCode", personTypeId), null, true);
		GenericValue data = EntityUtil.getFirst(dataList);
		String dictionaryTypeId = data.getString("dictionaryTypeId");
		// 各大区
		if (dictionaryTypeId.equals("AREA_DEPARTMENT")) {
		    List<GenericValue> childList = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("parentId", data.getString("dictionaryId")), null, true);
		    for (GenericValue child : childList) {
			String code = child.getString("dictionaryCode");
			baseIdList.add(code);
		    }
		} else {
		    // 各bu
		    baseIdList.add(personTypeId);
		}
	    }

	    EntityCondition mainCond = null;
	    List<EntityCondition> andExprs = FastList.newInstance();
	    if (UtilValidate.isNotEmpty(baseIdList)) {
		andExprs.add(EntityCondition.makeCondition("ownerBuId", EntityOperator.IN, baseIdList));
	    }
	    andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "Y"));
	    andExprs.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    if (andExprs.size() > 0) {
		mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);
	    }
	    // 按仓库统计 销售情况
	    List salesDataListByWarehouse = new ArrayList();

	    // 销售预警
	    List cautionSalesDataListByWarehouse = new ArrayList();

	    List orderBy = UtilMisc.toList("warehouseCode");
	    List<GenericValue> entityList = delegator.findList("CrmWmsInventory", mainCond, null, orderBy, null, true);

	    for (GenericValue entity : entityList) {
		Map<String, Object> map = FastMap.newInstance();
		Map<String, Object> cautionSalesDataMap = FastMap.newInstance();

		String id = entity.getString("id");
		// String ownerBuId = entity.getString("ownerBuId");
		String warehouseName = entity.getString("warehouseName");
		// 建设冷冻容量
		BigDecimal buildingFreeze = entity.getBigDecimal("buildingFreeze");
		buildingFreeze = UtilValidate.isEmpty(buildingFreeze) ? BigDecimal.ZERO : buildingFreeze;
		// 已使用冷冻
		BigDecimal physicalFreeze = entity.getBigDecimal("physicalFreeze");
		physicalFreeze = UtilValidate.isEmpty(physicalFreeze) ? BigDecimal.ZERO : physicalFreeze;
		// 剩余量
		// BigDecimal availableFreeze = buildingFreeze.subtract(physicalFreeze);

		// 建设冷藏容量
		BigDecimal buildingRefrigerate = entity.getBigDecimal("buildingRefrigerate");
		buildingRefrigerate = UtilValidate.isEmpty(buildingRefrigerate) ? BigDecimal.ZERO : buildingRefrigerate;
		// 已使用冷藏
		BigDecimal physicalRefrigerate = entity.getBigDecimal("physicalRefrigerate");
		physicalRefrigerate = UtilValidate.isEmpty(physicalRefrigerate) ? BigDecimal.ZERO : physicalRefrigerate;
		// BigDecimal availableRefrigerate =
		// buildingRefrigerate.subtract(physicalRefrigerate);

		// 建设恒温容量
		BigDecimal buildingConstant = entity.getBigDecimal("buildingConstant");
		buildingConstant = UtilValidate.isEmpty(buildingConstant) ? BigDecimal.ZERO : buildingConstant;
		// 已使用恒温
		BigDecimal physicalConstant = entity.getBigDecimal("physicalConstant");
		physicalConstant = UtilValidate.isEmpty(physicalConstant) ? BigDecimal.ZERO : physicalConstant;
		// BigDecimal availableConstant = buildingConstant.subtract(physicalConstant);

		// 建设常温容量
		BigDecimal buildingNormal = entity.getBigDecimal("buildingNormal");
		buildingNormal = UtilValidate.isEmpty(buildingNormal) ? BigDecimal.ZERO : buildingNormal;
		// 已使用常温
		BigDecimal physicalNormal = entity.getBigDecimal("physicalNormal");
		physicalNormal = UtilValidate.isEmpty(physicalNormal) ? BigDecimal.ZERO : physicalNormal;
		// BigDecimal availableNormal = buildingNormal.subtract(physicalNormal);

		BigDecimal buildingTotal = buildingFreeze.add(buildingRefrigerate).add(buildingConstant)
			.add(buildingNormal);

		// 已用库存小计
		BigDecimal physicalTotal = physicalFreeze.add(physicalRefrigerate).add(physicalConstant)
			.add(physicalNormal);

		// 可用库存小计
//		BigDecimal availableTotal = availableFreeze.add(availableRefrigerate).add(availableConstant)
//			.add(availableNormal);
		BigDecimal availableTotal = buildingTotal.subtract(physicalTotal);

//		Map estimatedInventory = getSaleInventory(delegator, id);
		Map estimatedInventory = getSaleInventoryFromDate2ThruDate(delegator, id, createTime_fld0_value,
			createTime_fld1_value, notFollowup);
		BigDecimal estimatedFreeze = (BigDecimal) estimatedInventory.get("estimatedFreeze");
		BigDecimal estimatedRefrigerate = (BigDecimal) estimatedInventory.get("estimatedRefrigerate");
		BigDecimal estimatedConstant = (BigDecimal) estimatedInventory.get("estimatedConstant");
		BigDecimal estimatedNormal = (BigDecimal) estimatedInventory.get("estimatedNormal");
		// 预测销售库存小计;
		BigDecimal estimatedTotal = estimatedFreeze.add(estimatedRefrigerate).add(estimatedConstant)
			.add(estimatedNormal);
		// 销售库位与空余库位占比

		BigDecimal availableTotalDivide = availableTotal;
		BigDecimal estimatedTotalDivide = estimatedTotal;

		if (availableTotalDivide.compareTo(BigDecimal.ONE) < 0) {
		    availableTotalDivide = BigDecimal.ONE;
		}
		if (availableTotalDivide.doubleValue() < 1) {
		    availableTotalDivide = BigDecimal.ONE;
		}
		if (estimatedTotalDivide.compareTo(BigDecimal.ONE) < 0) {
		    estimatedTotalDivide = BigDecimal.ONE;
		}

		if (estimatedTotalDivide.doubleValue() < 1) {
		    estimatedTotalDivide = BigDecimal.ONE;
		}

		// 总计销售库位与总计空余库位占比
		BigDecimal estimatedTotalRate = estimatedTotal.divide(availableTotalDivide, 2, BigDecimal.ROUND_HALF_UP)
			.multiply(new BigDecimal(100));

		// 总计空余库位与总计销售库位占比
		BigDecimal estimatedTotalRate2 = availableTotalDivide
			.divide(estimatedTotalDivide, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
		map.put("warehouseId", id);
		map.put("warehouseName", warehouseName);
		// map.put("estimatedDivAvailableRate", estimatedDivAvailableRate);
		// 已使用
		map.put("physicalFreeze", physicalFreeze);
		map.put("physicalRefrigerate", physicalRefrigerate);
		map.put("physicalConstant", physicalConstant);
		map.put("physicalNormal", physicalNormal);

		map.put("physicalTotal", physicalTotal);

		map.put("availableTotal", availableTotal);
		map.put("estimatedTotal", estimatedTotal);
		map.put("estimatedTotalRate", estimatedTotalRate);

		map.put("estimatedTotalRate2", estimatedTotalRate2);

		// 全温区
		map.put("estimatedFreeze", estimatedFreeze);
		map.put("estimatedRefrigerate", estimatedRefrigerate);
		map.put("estimatedConstant", estimatedConstant);
		map.put("estimatedNormal", estimatedNormal);

		BigDecimal availableFreeze = buildingFreeze.subtract(physicalFreeze);
		BigDecimal availableRefrigerate = buildingRefrigerate.subtract(physicalRefrigerate);
		BigDecimal availableConstant = buildingConstant.subtract(physicalConstant);
		BigDecimal availableNormal = buildingNormal.subtract(physicalNormal);

		map.put("availableFreeze", availableFreeze);
		map.put("availableRefrigerate", availableRefrigerate);
		map.put("availableConstant", availableConstant);
		map.put("availableNormal", availableNormal);

		map.put("estimatedFreezeRate", estimatedOtherRate(estimatedFreeze, availableFreeze));
		map.put("estimatedRefrigerateRate", estimatedOtherRate(estimatedRefrigerate, availableRefrigerate));
		map.put("estimatedConstantRate", estimatedOtherRate(estimatedConstant, availableConstant));
		map.put("estimatedNormalRate", estimatedOtherRate(estimatedNormal, availableNormal));

		map.put("estimatedFreezeRate2", estimatedOtherRate2(estimatedFreeze, availableFreeze));
		map.put("estimatedRefrigerateRate2", estimatedOtherRate2(estimatedRefrigerate, availableRefrigerate));
		map.put("estimatedConstantRate2", estimatedOtherRate2(estimatedConstant, availableConstant));
		map.put("estimatedNormalRate2", estimatedOtherRate2(estimatedNormal, availableNormal));

		map.put("estimatedFreezeRateNo",
			new BigDecimal(120).subtract((BigDecimal) map.get("estimatedFreezeRate")));
		map.put("estimatedRefrigerateRateNo",
			new BigDecimal(120).subtract((BigDecimal) map.get("estimatedRefrigerateRate")));
		map.put("estimatedConstantRateNo",
			new BigDecimal(120).subtract((BigDecimal) map.get("estimatedConstantRate")));
		map.put("estimatedNormalRateNo",
			new BigDecimal(120).subtract((BigDecimal) map.get("estimatedNormalRate")));

		salesDataListByWarehouse.add(map);

		cautionSalesDataMap.put("warehouseId", id);
		cautionSalesDataMap.put("warehouseName", warehouseName);

		// 已使用
		cautionSalesDataMap.put("physicalFreeze", physicalFreeze);
		cautionSalesDataMap.put("physicalRefrigerate", physicalRefrigerate);
		cautionSalesDataMap.put("physicalConstant", physicalConstant);
		cautionSalesDataMap.put("physicalNormal", physicalNormal);
		cautionSalesDataMap.put("physicalTotal", physicalTotal);

		cautionSalesDataMap.put("availableTotal", availableTotal);
		cautionSalesDataMap.put("estimatedTotal", estimatedTotal);
		cautionSalesDataMap.put("estimatedTotalRate", estimatedTotalRate);
		cautionSalesDataMap.put("estimatedTotalRate2", estimatedTotalRate2);
		cautionSalesDataMap.put("estimatedTotalRateNo", new BigDecimal(120).subtract(estimatedTotalRate));

//		if (estimatedTotalRate.compareTo(new BigDecimal(100)) < 0) {
//		    cautionSalesDataMap.put("estimatedTotalRate100", new BigDecimal(120).subtract(estimatedTotalRate));
//		}
//		if (estimatedTotalRate.compareTo(new BigDecimal(100)) > 0) {
//		    cautionSalesDataMap.put("estimatedTotalRate200", new BigDecimal(120).subtract(estimatedTotalRate));
//		}
//			}
//
//		if (estimatedTotalRateDisplay ) {
		cautionSalesDataListByWarehouse.add(cautionSalesDataMap);
//			}

	    } // 循环结束

	    Map<String, Object> workMap = FastMap.newInstance();

	    workMap.put("customerListByProductCategory",
		    customerNewListByProductCategory(delegator, baseIdList, ownerUserId));
	    // workMap.put("businessListByProductCategory",
	    // businessListByProductCategory(delegator,"month"));

	    workMap.put("salesDataListByWarehouse", salesDataListByWarehouse);// 汇总

	    Map allMap = FastMap.newInstance();
	    allMap.put("warehouseId", "_NA_");
	    allMap.put("warehouseName", "汇总");
	    BigDecimal physicalFreeze = BigDecimal.ZERO;
	    BigDecimal physicalRefrigerate = BigDecimal.ZERO;
	    BigDecimal physicalConstant = BigDecimal.ZERO;
	    BigDecimal physicalNormal = BigDecimal.ZERO;
	    BigDecimal physicalTotal = BigDecimal.ZERO;
	    BigDecimal availableFreeze = BigDecimal.ZERO;
	    BigDecimal estimatedFreeze = BigDecimal.ZERO;
	    BigDecimal estimatedFreezeRate = BigDecimal.ZERO;
	    BigDecimal availableRefrigerate = BigDecimal.ZERO;
	    BigDecimal estimatedRefrigerate = BigDecimal.ZERO;
	    BigDecimal estimatedRefrigerateRate = BigDecimal.ZERO;
	    BigDecimal availableConstant = BigDecimal.ZERO;
	    BigDecimal estimatedConstant = BigDecimal.ZERO;
	    BigDecimal estimatedConstantRate = BigDecimal.ZERO;
	    BigDecimal availableNormal = BigDecimal.ZERO;
	    BigDecimal estimatedNormal = BigDecimal.ZERO;
	    BigDecimal estimatedNormalRate = BigDecimal.ZERO;
	    BigDecimal availableTotal = BigDecimal.ZERO;
	    BigDecimal estimatedTotal = BigDecimal.ZERO;
	    BigDecimal estimatedTotalRate = BigDecimal.ZERO;
	    for (Object item : salesDataListByWarehouse) {
		Map info = (Map) item;
		if (UtilValidate.isNotEmpty(info.get("physicalFreeze"))) {
		    physicalFreeze = physicalFreeze.add((BigDecimal) info.get("physicalFreeze"));
		}
		if (UtilValidate.isNotEmpty(info.get("physicalRefrigerate"))) {
		    physicalRefrigerate = physicalRefrigerate.add((BigDecimal) info.get("physicalRefrigerate"));
		}
		if (UtilValidate.isNotEmpty(info.get("physicalConstant"))) {
		    physicalConstant = physicalConstant.add((BigDecimal) info.get("physicalConstant"));
		}
		if (UtilValidate.isNotEmpty(info.get("physicalNormal"))) {
		    physicalNormal = physicalNormal.add((BigDecimal) info.get("physicalNormal"));
		}
		if (UtilValidate.isNotEmpty(info.get("physicalTotal"))) {
		    physicalTotal = physicalTotal.add((BigDecimal) info.get("physicalTotal"));
		}
		if (UtilValidate.isNotEmpty(info.get("availableFreeze"))) {
		    availableFreeze = availableFreeze.add((BigDecimal) info.get("availableFreeze"));
		}
		if (UtilValidate.isNotEmpty(info.get("estimatedFreeze"))) {
		    estimatedFreeze = estimatedFreeze.add((BigDecimal) info.get("estimatedFreeze"));
		}
		if (UtilValidate.isNotEmpty(info.get("estimatedFreezeRate"))) {
		    estimatedFreezeRate = estimatedFreezeRate.add((BigDecimal) info.get("estimatedFreezeRate"));
		}
		if (UtilValidate.isNotEmpty(info.get("availableRefrigerate"))) {
		    availableRefrigerate = availableRefrigerate.add((BigDecimal) info.get("availableRefrigerate"));
		}
		if (UtilValidate.isNotEmpty(info.get("estimatedRefrigerate"))) {
		    estimatedRefrigerate = estimatedRefrigerate.add((BigDecimal) info.get("estimatedRefrigerate"));
		}
		if (UtilValidate.isNotEmpty(info.get("estimatedRefrigerateRate"))) {
		    estimatedRefrigerateRate = estimatedRefrigerateRate
			    .add((BigDecimal) info.get("estimatedRefrigerateRate"));
		}
		if (UtilValidate.isNotEmpty(info.get("availableConstant"))) {
		    availableConstant = availableConstant.add((BigDecimal) info.get("availableConstant"));
		}
		if (UtilValidate.isNotEmpty(info.get("estimatedConstant"))) {
		    estimatedConstant = estimatedConstant.add((BigDecimal) info.get("estimatedConstant"));
		}
		if (UtilValidate.isNotEmpty(info.get("estimatedConstantRate"))) {
		    estimatedConstantRate = estimatedConstantRate.add((BigDecimal) info.get("estimatedConstantRate"));
		}
		if (UtilValidate.isNotEmpty(info.get("availableNormal"))) {
		    availableNormal = availableNormal.add((BigDecimal) info.get("availableNormal"));
		}
		if (UtilValidate.isNotEmpty(info.get("estimatedNormal"))) {
		    estimatedNormal = estimatedNormal.add((BigDecimal) info.get("estimatedNormal"));
		}
		if (UtilValidate.isNotEmpty(info.get("estimatedNormalRate"))) {
		    estimatedNormalRate = estimatedNormalRate.add((BigDecimal) info.get("estimatedNormalRate"));
		}
		if (UtilValidate.isNotEmpty(info.get("availableTotal"))) {
		    availableTotal = availableTotal.add((BigDecimal) info.get("availableTotal"));
		}
		if (UtilValidate.isNotEmpty(info.get("estimatedTotal"))) {
		    estimatedTotal = estimatedTotal.add((BigDecimal) info.get("estimatedTotal"));
		}
	    }
//	    if (availableTotal.doubleValue() < 1) {
//		availableTotal = BigDecimal.ONE;
//	    }
	    BigDecimal availableTotalDivie = availableTotal;
	    if (availableTotalDivie.doubleValue() < 1) {
		availableTotalDivie = BigDecimal.ONE;
	    }

	    estimatedTotalRate = estimatedTotal.divide(availableTotalDivie, 2, BigDecimal.ROUND_HALF_UP)
		    .multiply(new BigDecimal(100));
	    allMap.put("physicalFreeze", physicalFreeze);
	    allMap.put("physicalRefrigerate", physicalRefrigerate);
	    allMap.put("physicalConstant", physicalConstant);
	    allMap.put("physicalNormal", physicalNormal);
	    allMap.put("physicalTotal", physicalTotal);

	    allMap.put("availableFreeze", availableFreeze);
	    allMap.put("estimatedFreeze", estimatedFreeze);
	    allMap.put("estimatedFreezeRate", estimatedFreezeRate);

	    allMap.put("availableRefrigerate", availableRefrigerate);
	    allMap.put("estimatedRefrigerate", estimatedRefrigerate);
	    allMap.put("estimatedRefrigerateRate", estimatedRefrigerateRate);

	    allMap.put("availableConstant", availableConstant);
	    allMap.put("estimatedConstant", estimatedConstant);
	    allMap.put("estimatedConstantRate", estimatedConstantRate);

	    allMap.put("availableNormal", availableNormal);
	    allMap.put("estimatedNormal", estimatedNormal);
	    allMap.put("estimatedNormalRate", estimatedNormalRate);

	    allMap.put("availableTotal", availableTotal);
	    allMap.put("estimatedTotal", estimatedTotal);
	    allMap.put("estimatedTotalRate", estimatedTotalRate);
//	    salesDataListByWarehouse.add(allMap);
	    workMap.put("salesDataListByWarehouseHuizong", allMap);
	    workMap.put("cautionSalesDataListByWarehouse", cautionSalesDataListByWarehouse);

	    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    String fromDateDateFormat = simpleDateFormat.format(createTime_fld0_value);
	    String thruDateDateFormat = simpleDateFormat.format(createTime_fld1_value);
	    workMap.put("fromDate", fromDateDateFormat);
	    workMap.put("thruDate", thruDateDateFormat);

	    result.put("workMap", workMap);
	    Debug.log("getSalesDataTotalAnalysis == end");
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    public static BigDecimal estimatedOtherRate(BigDecimal estimatedTotal, BigDecimal availableTotal) {

	BigDecimal availableTotalDivide = availableTotal;
	BigDecimal estimatedTotalDivide = estimatedTotal;

	if (availableTotalDivide.compareTo(BigDecimal.ONE) < 0) {
	    availableTotalDivide = BigDecimal.ONE;
	}
	if (availableTotalDivide.doubleValue() < 1) {
	    availableTotalDivide = BigDecimal.ONE;
	}
	if (estimatedTotalDivide.compareTo(BigDecimal.ONE) < 0) {
	    estimatedTotalDivide = BigDecimal.ONE;
	}

	if (estimatedTotalDivide.doubleValue() < 1) {
	    estimatedTotalDivide = BigDecimal.ONE;
	}

	// 总计销售库位与总计空余库位占比
	BigDecimal estimatedTotalRate = estimatedTotal.divide(availableTotalDivide, 2, BigDecimal.ROUND_HALF_UP)
		.multiply(new BigDecimal(100));
	return estimatedTotalRate;

    }

    public static BigDecimal estimatedOtherRate2(BigDecimal estimatedTotal, BigDecimal availableTotal) {

	BigDecimal availableTotalDivide = availableTotal;
	BigDecimal estimatedTotalDivide = estimatedTotal;

	if (availableTotalDivide.compareTo(BigDecimal.ONE) < 0) {
	    availableTotalDivide = BigDecimal.ONE;
	}
	if (availableTotalDivide.doubleValue() < 1) {
	    availableTotalDivide = BigDecimal.ONE;
	}
	if (estimatedTotalDivide.compareTo(BigDecimal.ONE) < 0) {
	    estimatedTotalDivide = BigDecimal.ONE;
	}

	if (estimatedTotalDivide.doubleValue() < 1) {
	    estimatedTotalDivide = BigDecimal.ONE;
	}

	// 总计空余库位与总计销售库位占比
	BigDecimal estimatedTotalRate2 = availableTotalDivide.divide(estimatedTotalDivide, 2, BigDecimal.ROUND_HALF_UP)
		.multiply(new BigDecimal(100));

	return estimatedTotalRate2;
    }

    public static Map<String, List> getBuList(String userLoginId, String personTypeId) {
	Delegator delegator = DelegatorFactory.getDelegator("default");
	List<String> list = FastList.newInstance();
	List<Map<String, Object>> mapList = FastList.newInstance();
	try {
	    List<GenericValue> buList = delegator.findByAnd("DataDictionary",
		    UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT"), UtilMisc.toList("sequenceId"), true);
	    List<GenericValue> shipList = delegator.findByAnd("CoRelationship",
		    UtilMisc.toMap("partyIdTo", userLoginId), null, true);
	    String buName = "";
	    String buCode = "";
	    String sequenceId = "";
	    if (UtilValidate.isNotEmpty(shipList)) {
		buCode = EntityUtil.getFirst(shipList).getString("partyIdFrom");
		if (UtilValidate.isNotEmpty(buCode)) {
		    List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("dictionaryCode", buCode), UtilMisc.toList("sequenceId"), true);
		    GenericValue data = EntityUtil.getFirst(dataList);
		    if (UtilValidate.isNotEmpty(buCode)) {
			buName = data.getString("description");
			sequenceId = data.getString("sequenceId"); 
		    }

		}
	    }

	    if (personTypeId.equals("2")) { // 本bu
		List<String> users = FastList.newInstance();
		// 本bu下的人员
		List<GenericValue> buShipList = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdFrom", buCode), UtilMisc.toList("-partyIdTo"), true);
		if (UtilValidate.isNotEmpty(buShipList)) {
		    for (GenericValue item : buShipList) {
			String userLoginId1 = item.getString("partyIdTo");
			if (!users.contains(userLoginId1)) {
			    users.add(userLoginId1);
			}
		    }
		}
		users = users.stream().distinct().collect(Collectors.toList());
		list.addAll(users);
		mapList.add(UtilMisc.toMap("buId", buCode, "buName", buName,"sequenceId",sequenceId, "list", users));

	    } else if ("allData".equals(personTypeId)) { // 全国
		// 所有bu
		x: for (GenericValue bu : buList) {
		    String dictionaryCode2 = bu.getString("dictionaryCode2");
		    if ("N".equals(dictionaryCode2)) {
			continue x;
		    }
		    List<Map<String, Object>> buPersonList1 = FastList.newInstance();
		    List<GenericValue> itemShipList = delegator.findByAnd("CoRelationship",
			    UtilMisc.toMap("partyIdFrom", bu.getString("dictionaryCode")),
			    UtilMisc.toList("-partyIdTo"), true);

		    List<String> users = FastList.newInstance();
		    if (UtilValidate.isNotEmpty(itemShipList)) {
			for (GenericValue item : itemShipList) {
			    if (!users.contains(item.getString("partyIdTo"))) {
				users.add(item.getString("partyIdTo"));
			    }
			}
		    }
		    users = users.stream().distinct().collect(Collectors.toList());
		    list.addAll(users);
		    mapList.add(UtilMisc.toMap("buId", bu.getString("dictionaryCode"), "buName",
			    bu.getString("description"),"sequenceId",bu.getString("sequenceId"), "list", users));
		}
	    } else if ("3".equals(personTypeId)) { // 本大区
		List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryCode", buCode), UtilMisc.toList("sequenceId"), true);
		GenericValue data = EntityUtil.getFirst(dataList);
		// 本大区下的所有bu
		List<GenericValue> sunBuList = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT", "parentId", data.getString("parentId")),
			UtilMisc.toList("sequenceId"), true);
		x: for (GenericValue bu : sunBuList) {
		    List<String> users = FastList.newInstance();
		    String dictionaryCode2 = bu.getString("dictionaryCode2");
		    if ("N".equals(dictionaryCode2)) {
			continue x;
		    }
		    List<GenericValue> itemShipList = delegator.findByAnd("CoRelationship",
			    UtilMisc.toMap("partyIdFrom", bu.getString("dictionaryCode")),
			    UtilMisc.toList("-partyIdTo"), true);
		    if (UtilValidate.isNotEmpty(itemShipList)) {
			for (GenericValue item : itemShipList) {
			    String userLoginId1 = item.getString("partyIdTo");
			    if (!users.contains(item.getString("partyIdTo"))) {
				users.add(item.getString("partyIdTo"));
			    }
			}
		    }
		    users = users.stream().distinct().collect(Collectors.toList());
		    list.addAll(users);
		    mapList.add(UtilMisc.toMap("buId", bu.getString("dictionaryCode"), "buName",
			    bu.getString("description"),"sequenceId",bu.getString("sequenceId"), "list", users));
		}

	    } else {
		boolean isThru = false;
		if (personTypeId.contains(",")) {
		    isThru = true;
		}
		if (isThru == false) {
		    List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("dictionaryCode", personTypeId), null, true);
		    GenericValue data = EntityUtil.getFirst(dataList);
		    String dictionaryTypeId = data.getString("dictionaryTypeId");
		    // 各大区
		    if (dictionaryTypeId.equals("AREA_DEPARTMENT")) {
			// 各大区下的人员
			List<GenericValue> sunBuList = delegator
				.findByAnd(
					"DataDictionary", UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT",
						"parentId", data.getString("dictionaryId")),
					UtilMisc.toList("sequenceId"), true);
			x: for (GenericValue bu : sunBuList) {
			    String dictionaryCode2 = bu.getString("dictionaryCode2");
			    if ("N".equals(dictionaryCode2)) {
				continue x;
			    }
			    List<String> users = FastList.newInstance();
			    List<GenericValue> itemShipList = delegator.findByAnd("CoRelationship",
				    UtilMisc.toMap("partyIdFrom", bu.getString("dictionaryCode")),
				    UtilMisc.toList("-partyIdTo"), true);
			    if (UtilValidate.isNotEmpty(itemShipList)) {
				for (GenericValue item : itemShipList) {
				    if (!users.contains(item.getString("partyIdTo"))) {
					users.add(item.getString("partyIdTo"));
				    }
				}
				users = users.stream().distinct().collect(Collectors.toList());
				list.addAll(users);
				mapList.add(UtilMisc.toMap("buId", bu.getString("dictionaryCode"), "buName",
					bu.getString("description"),"sequenceId",bu.getString("sequenceId"), "list", users));
			    }
			}
		    } else {
			// 各bu
			List<GenericValue> itemShipList = delegator.findByAnd("CoRelationship",
				UtilMisc.toMap("partyIdFrom", personTypeId), UtilMisc.toList("-partyIdTo"), true);
			List<String> users = FastList.newInstance();
			if (UtilValidate.isNotEmpty(itemShipList)) {
			    for (GenericValue item : itemShipList) {
				if (!users.contains(item.getString("partyIdTo"))) {
				    users.add(item.getString("partyIdTo"));
				}
			    }
			}
			users = users.stream().distinct().collect(Collectors.toList());
			list.addAll(users);
			List<GenericValue> dataList1 = delegator.findByAnd("DataDictionary",
				UtilMisc.toMap("dictionaryCode", personTypeId), UtilMisc.toList("sequenceId"), true);
			GenericValue data1 = EntityUtil.getFirst(dataList1);
			String name = data1.getString("description");
			String sequenceId1 = data1.getString("sequenceId");
			
			mapList.add(UtilMisc.toMap("buId", personTypeId, "buName", name,"sequenceId",sequenceId1, "list", users));
		    }
		} else {
		    List<String> buIdList = CommonUtils.splitCustomStringToList(personTypeId, ",");
		    for (String buId : buIdList) {
			// 各bu
			List<GenericValue> itemShipList = delegator.findByAnd("CoRelationship",
				UtilMisc.toMap("partyIdFrom", buId), UtilMisc.toList("-partyIdTo"), true);
			List<String> users = FastList.newInstance();
			if (UtilValidate.isNotEmpty(itemShipList)) {
			    for (GenericValue item : itemShipList) {
				if (!users.contains(item.getString("partyIdTo"))) {
				    users.add(item.getString("partyIdTo"));
				}
			    }
			}
			users = users.stream().distinct().collect(Collectors.toList());
			list.addAll(users);
			List<GenericValue> dataList1 = delegator.findByAnd("DataDictionary",
				UtilMisc.toMap("dictionaryCode", buId), UtilMisc.toList("sequenceId"), true);
			GenericValue data1 = EntityUtil.getFirst(dataList1);
			String name = data1.getString("description");
			String sequenceId1 = data1.getString("sequenceId");
			mapList.add(UtilMisc.toMap("buId", buId, "buName", name,"sequenceId",sequenceId1, "list", users));
		    }
		}

	    }
	    if (UtilValidate.isNotEmpty(list)) {
		list = list.stream().distinct().collect(Collectors.toList());
	    }
	} catch (GenericEntityException e) {
	    e.printStackTrace();
	}
	Map<String, List> map = FastMap.newInstance();
	map.put("list", list);
	map.put("mapList", mapList);
	return map;
    }

// 签约报告2。0
    public static Map<String, Object> getNewSigningAnalysis(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String typeId = (String) context.get("typeId");
	String personTypeId = (String) context.get("personTypeId");
	String warehouseId = (String) context.get("warehouseId");
	String createTime_fld0_value = (String) context.get("createTime_fld0_value"); // 开始时间
	String createTime_fld1_value = (String) context.get("createTime_fld1_value"); // 结束时间
	String ownerUserId = userLogin.getString("userLoginId");
	// 人员
	List<String> partyIdList = FastList.newInstance();
	List<Map<String, Object>> buPersonList = FastList.newInstance();
	List<Map<String, Object>> whouseList = FastList.newInstance();
	List<String> buIdList = FastList.newInstance();
	try {
	    // 根据开始时间 结束时间. 获取一个坐标列表
	    if (UtilValidate.isEmpty(createTime_fld0_value) && UtilValidate.isEmpty(createTime_fld1_value)) {
		createTime_fld0_value = CommonUtils.getLastMonth();
		createTime_fld1_value = CommonUtils.getNowMonth();
	    }
	    List<String> timeList = CommonUtils.getMonthList(createTime_fld0_value, createTime_fld1_value);

	    List ownerUserIdList = new ArrayList();
	    if (UtilValidate.isEmpty(personTypeId)) {
		personTypeId = "2";
	    }
	    if ("nowData".equals(personTypeId)) {
		partyIdList = UtilMisc.toList(userLogin.getString("userLoginId"));

		Map<String, List> map12 = getBuList(ownerUserId, "2");
		buPersonList = map12.get("mapList");
	    } else {
		Map<String, List> map12 = getBuList(ownerUserId, personTypeId);
		buPersonList = map12.get("mapList");
		partyIdList = map12.get("list");
	    }

	    // 获取有效仓库列表
	    for (Map<String, Object> map : buPersonList) {
		if (!buIdList.contains(map.get("buId"))) {
		    buIdList.add((String) map.get("buId"));
		}
	    }

	    List<GenericValue> invList = FastList.newInstance();
	    if (typeId.equals("1")) {
	    } else {
		List mainCond1 = new ArrayList();
		if (UtilValidate.isNotEmpty(buIdList)) {
		    mainCond1.add(EntityCondition.makeCondition("ownerBuId", EntityOperator.IN, buIdList));
		}
		mainCond1.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
		mainCond1.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "Y"));

		invList = delegator.findList("CrmWmsInventory",
			EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null,
			UtilMisc.toList("-createTime"), null, true);

	    }
	    List<Map<String, Object>> mapList = FastList.newInstance();
	    List<Map<String, Object>> infoMapList = FastList.newInstance();

	    List<Map<String, Object>> buChartList = FastList.newInstance();

//	    Map<String, Map<String, Object>> buMap = FastMap.newInstance();

	    Map<String, Object> hzMap = FastMap.newInstance();

	    hzMap.put("warehouseName", "汇总");
	    hzMap.put("name", "汇总");
	    hzMap.put("buId", "_NA_");
	    hzMap.put("whouseId", "_NA_");
	    Map<String, List<GenericValue>> itemMap = FastMap.newInstance();
	    for (String time : timeList) {
		List<String> idList = FastList.newInstance();
		EntityCondition mainCond = null;
		List<EntityCondition> andExprs = FastList.newInstance();

//		if (UtilValidate.isNotEmpty(buIdList)) {
//		    andExprs.add(EntityCondition.makeCondition("partyIdFrom", EntityOperator.IN, buIdList));
//		}

		if (UtilValidate.isNotEmpty(partyIdList)) {
		    andExprs.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, partyIdList));
		}

		if (typeId.equals("2")) {
		    andExprs.add(EntityCondition.makeCondition("whouseId", EntityOperator.NOT_EQUAL, "_NA_"));
		    andExprs.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "1"));
		}

		andExprs.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

		andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("5")));

		// 最小日期 最大日期
		Map<String, Timestamp> dateMap = CommonUtils.getNowMonthDay(time);
		andExprs.add(EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO,
			dateMap.get("startDate")));
		andExprs.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO,
			dateMap.get("endDate")));
		if (andExprs.size() > 0) {
		    mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);
		}
		List<GenericValue> itemList = delegator.findList("CrmBusinessItemBuByTypeId2", mainCond, null,
			UtilMisc.toList("-status5Time"), null, true);

		for (GenericValue item : itemList) {
		    String whouseId = item.getString("whouseId");
		    String warehouseName = item.getString("warehouseName");
		    String warehouseCode = item.getString("warehouseCode");
		    if (UtilValidate.isEmpty(warehouseCode))
			warehouseCode = "100000";
		    Map map1 = UtilMisc.toMap("whouseId", whouseId, "warehouseCode", warehouseCode, "warehouseName",
			    warehouseName);
		    if (!whouseList.contains(map1)) {
			whouseList.add(map1);
		    }
		}
		itemMap.put(time, itemList);
	    }
	    List<Map<String, Object>> delWhouseList = FastList.newInstance();
	    for (Map<String, Object> whouse : whouseList) {
		String whouseId1 = (String) whouse.get("whouseId");
		boolean isOk = false;
		for (GenericValue inv : invList) {
		    String whouseId = inv.getString("id");
		    if (whouseId1.equals(whouseId)) {
			isOk = true;
		    }
		}
		if (isOk == false) {
		    delWhouseList.add(whouse);
		}
	    }

	    whouseList.removeAll(delWhouseList);

//	    Collections.sort(whouseList, new Comparator<Map>() {
//		@Override
//		public int compare(Map obj1, Map obj2) {
//		    int i = ((String) obj1.get("warehouseCode")).compareTo((String) obj2.get("warehouseCode"));
//		    return i;
//		}
//	    });
	    List<String> buList = FastList.newInstance();
	    Map<String, Map<String, Object>> buMap = FastMap.newInstance();

	    List<String> checkWhouseList = FastList.newInstance();
	    Map<String, Map<String, Object>> whouseMap = FastMap.newInstance();

	    for (String time : timeList) {

		List<GenericValue> itemList = new ArrayList();
		if (UtilValidate.isNotEmpty(itemMap.get(time))) {
		    itemList = itemMap.get(time);
		}
		Map<String, Object> map = FastMap.newInstance();
		map.put("key", time);
		BigDecimal amount = BigDecimal.ZERO;

		List<Map<String, Object>> successList = FastList.newInstance();
		List<Map<String, Object>> successList2 = FastList.newInstance();
		for (GenericValue item : itemList) {
		    GenericValue entity = delegator.findOne("CrmBusiness", true,
			    UtilMisc.toMap("id", item.getString("businessId")));
		    Map map1 = buildCrmBusinessByWhouseId(delegator, entity, item.getString("itemId"));
		    if (!successList.contains(map1)) {
			successList.add(map1);
		    }
//		    Map map2 = UtilMisc.toMap("ownerUserId_dictText",map1.get("ownerUserId_dictText"),
//			    "typeId_dictText",map1.get("typeId_dictText"),"warehouseName",map1.get("warehouseName")
//			    ,"customerId_dictText",map1.get("customerId_dictText"),"estimatedSalesAmount",map1.get("estimatedSalesAmount")
//			    ,"id",map1.get("id"),"businessId",map1.get("businessId"));
//		    System.out.println(map2);
//		    if(!successList2.contains(map2)) {
//			successList2.add(map2);
//		    }

		}

		for (Map item : successList) {
		    BigDecimal itemAount = (BigDecimal) item.get("estimatedSalesAmount");
		    if (typeId.equals("1")) {
			if (UtilValidate.isNotEmpty(itemAount)) {
			    amount = amount.add(itemAount);
			}
		    } else {
			String whouseId = (String) item.get("whouseId");
			boolean isOk = false;
			for (Map<String, Object> whouse : whouseList) {
			    String whouseId1 = (String) whouse.get("whouseId");
			    String warehouseName1 = (String) whouse.get("warehouseName");
			    if (whouseId1.equals(whouseId)) {
				isOk = true;
			    }
			}
			if (isOk == true) {
			    if (UtilValidate.isNotEmpty(itemAount)) {
				amount = amount.add(itemAount);
			    }
			}
		    }

		}

		map.put("value", amount);
		mapList.add(map);

		BigDecimal timeAmount = BigDecimal.ZERO;
		// BU
		if (typeId.equals("1")) {

		    for (Map<String, Object> buPerson : buPersonList) {
			String buId1 = (String) buPerson.get("buId");
			String buName1 = (String) buPerson.get("buName");
			String sequenceId1 = (String) buPerson.get("sequenceId");
			List<String> personList = (List<String>) buPerson.get("list");
			Debug.log("buId1 = " + buId1 + ", buName1 = " + buName1);
			if (!buList.contains(buId1)) {
			    buList.add(buId1);
			    Map<String, Object> infoMap = FastMap.newInstance();
			    infoMap.put("buId", buId1);
			    infoMap.put("name", buName1);
			    infoMap.put("sequenceId", sequenceId1);
			    infoMap.put(time, BigDecimal.ZERO);
			    buMap.put(buId1, infoMap);
			    Debug.log("buId1 = " + buId1 + ", buMap = " + buMap);
			} else {
			    Map<String, Object> infoMap = buMap.get(buId1);
			    Debug.log(" buMap = " + buMap);
			    Debug.log("buId1 = " + buId1 + ", infoMap = " + infoMap);
			    BigDecimal oldAmount = (BigDecimal) infoMap.get(time);
			    if (UtilValidate.isEmpty(oldAmount))
				oldAmount = BigDecimal.ZERO;
			    infoMap.put(time, oldAmount);
			    buMap.put(buId1, infoMap);
			}

			for (Map item : successList) {
			    BigDecimal itemAount1 = (BigDecimal) item.get("estimatedSalesAmount");
			    String ownerUserId1 = (String) item.get("ownerUserId");

			    if (UtilValidate.isEmpty(itemAount1)) {
				itemAount1 = BigDecimal.ZERO;
			    }
			    // 说明数据是这个bu下的数据
			    if (personList.contains(ownerUserId1)) {
				timeAmount = timeAmount.add(itemAount1);
				Map<String, Object> infoMap = buMap.get(buId1);
				BigDecimal oldAmount = (BigDecimal) infoMap.get(time);
				if (UtilValidate.isEmpty(oldAmount))
				    oldAmount = BigDecimal.ZERO;
				oldAmount = oldAmount.add(itemAount1);
				infoMap.put(time, oldAmount);
				buMap.put(buId1, infoMap);
			    }
			}
		    }

		} else {

		    // 仓库
		    for (Map<String, Object> whouse : whouseList) {
			String whouseId1 = (String) whouse.get("whouseId");
			String warehouseName1 = (String) whouse.get("warehouseName");
			String warehouseCode1 = (String) whouse.get("warehouseCode");

			if (!checkWhouseList.contains(whouseId1)) {
			    checkWhouseList.add(whouseId1);
			    Map<String, Object> infoMap = FastMap.newInstance();
			    infoMap.put("whouseId", whouseId1);
			    infoMap.put("warehouseName", warehouseName1);
			    infoMap.put("warehouseCode", warehouseCode1);
			    infoMap.put(time, BigDecimal.ZERO);
			    whouseMap.put(whouseId1, infoMap);
			} else {
			    Map<String, Object> infoMap = whouseMap.get(whouseId1);
			    BigDecimal oldAmount = (BigDecimal) infoMap.get(time);
			    if (UtilValidate.isEmpty(oldAmount))
				oldAmount = BigDecimal.ZERO;
			    infoMap.put(time, oldAmount);
			    whouseMap.put(whouseId1, infoMap);
			}

			for (Map item : successList) {
			    String whouseId = (String) item.get("whouseId");
			    BigDecimal itemAount1 = (BigDecimal) item.get("estimatedSalesAmount");
			    if (UtilValidate.isEmpty(itemAount1)) {
				itemAount1 = BigDecimal.ZERO;
			    }

			    if (whouseId1.equals(whouseId)) {
				timeAmount = timeAmount.add(itemAount1);
				Map<String, Object> infoMap = whouseMap.get(whouseId);
				BigDecimal oldAmount = (BigDecimal) infoMap.get(time);
				if (UtilValidate.isEmpty(oldAmount))
				    oldAmount = BigDecimal.ZERO;
				oldAmount = oldAmount.add(itemAount1);
				infoMap.put(time, oldAmount);
				whouseMap.put(whouseId, infoMap);
			    }
			}
		    }

		}
		hzMap.put(time, timeAmount);

	    }

	    if (UtilValidate.isNotEmpty(buMap)) {

		for (String m : buMap.keySet()) {
		    buChartList.add(buMap.get(m));
		}
		Collections.sort(buChartList, new Comparator<Map>() {
		    @Override
		    public int compare(Map obj1, Map obj2) {
			int i = ((String) obj1.get("sequenceId")).compareTo((String) obj2.get("sequenceId"));
			return i;
		    }
		});

	    }

	    if (UtilValidate.isNotEmpty(whouseMap)) {

		for (String m : whouseMap.keySet()) {
		    buChartList.add(whouseMap.get(m));
		}

		Collections.sort(buChartList, new Comparator<Map>() {
		    @Override
		    public int compare(Map obj1, Map obj2) {
			int i = ((String) obj1.get("warehouseCode")).compareTo((String) obj2.get("warehouseCode"));
			return i;
		    }
		});
	    }

//	    for (String m : buMap.keySet()) {
//		buChartList.add(buMap.get(m));
//	    }
	    // 汇总
	    buChartList.add(hzMap);
	    Map<String, Object> workMap = FastMap.newInstance();
	    workMap.put("chartList", mapList);

	    workMap.put("buChartList", buChartList);
	    result.put("workMap", workMap);
	} catch (

	GenericEntityException e) {
	    e.printStackTrace();
	}
	return result;
    }

// 签约报告2.0
    public static Map<String, Object> getNewSigningAnalysisList(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String typeId = (String) context.get("typeId");
	String orderBy = (String) context.get("orderBy");
	String buId = (String) context.get("buId");
	String personTypeId = (String) context.get("personTypeId");
	String createTime_fld0_value = (String) context.get("createTime_fld0_value"); // 开始时间
	String createTime_fld1_value = (String) context.get("createTime_fld1_value"); // 结束时间
	String ownerUserId = userLogin.getString("userLoginId");
	// 人员
	List<String> partyIdList = FastList.newInstance();
	List successList = FastList.newInstance();
	try {
	    // 根据开始时间 结束时间. 获取一个坐标列表
	    if (UtilValidate.isEmpty(createTime_fld0_value) && UtilValidate.isEmpty(createTime_fld1_value)) {
		createTime_fld0_value = CommonUtils.getLastMonth();
		createTime_fld1_value = CommonUtils.getNowMonth();
	    }
	    List<String> timeList = CommonUtils.getMonthList(createTime_fld0_value, createTime_fld1_value);

	    if (typeId.equals("1")) {
		if (UtilValidate.isEmpty(personTypeId)) {
		    personTypeId = "2";
		}
		Map<String, List> map = getBuList(ownerUserId, personTypeId);
		partyIdList = map.get("list");

		if ("nowData".equals(buId)) {
		    partyIdList = UtilMisc.toList(ownerUserId);
		}
	    } else {
		Map<String, List> map = getBuList(ownerUserId, buId);
		partyIdList = map.get("list");
		if ("nowData".equals(buId)) {
		    partyIdList = UtilMisc.toList(ownerUserId);
		}
	    }

	    for (String time : timeList) {
		List<String> idList = FastList.newInstance();
		EntityCondition mainCond = null;
		List<EntityCondition> andExprs = FastList.newInstance();

		andExprs.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, partyIdList));

		if (typeId.equals("2")) {
		    List<String> whouseIdList = CommonUtils.splitCustomStringToList(personTypeId, ",");
		    andExprs.add(EntityCondition.makeCondition("whouseId", EntityOperator.IN, whouseIdList));

		    andExprs.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "1"));
		}

		andExprs.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

		// 最小日期 最大日期
		Map<String, Timestamp> dateMap = CommonUtils.getNowMonthDay(time);
		andExprs.add(EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO,
			dateMap.get("startDate")));
		andExprs.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO,
			dateMap.get("endDate")));

		andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("5")));

		if (andExprs.size() > 0) {
		    mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);
		}
		List orderList = UtilMisc.toList("-status5Time");

		if (UtilValidate.isNotEmpty(orderBy)) {
		    orderList = UtilMisc.toList(orderBy);
		}
		List<GenericValue> itemList = delegator.findList("CrmBusinessItemBuByTypeId2", mainCond, null,
			orderList, null, true);

		for (GenericValue item : itemList) {
		    if (!idList.contains(item.getString("businessId"))) {
			idList.add(item.getString("businessId"));
		    }
		    GenericValue entity = delegator.findOne("CrmBusiness", true,
			    UtilMisc.toMap("id", item.getString("businessId")));
		    Map map = buildCrmBusinessByWhouseId(delegator, entity, item.getString("itemId"));
		    if (!successList.contains(map)) {
			successList.add(map);
		    }
		}
	    }
	    Collections.sort(successList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
			if(UtilValidate.isEmpty(obj2.get("status5Time"))){return 0;}
			
			int i = ((Timestamp) obj2.get("status5Time")).compareTo((Timestamp) obj1.get("status5Time"));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    Map<String, Object> workMap = FastMap.newInstance();
	    workMap.put("successCrmBusinessTotalAmountList", successList);
	    result.put("workMap", workMap);
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

// 商机报告 新的
    public static Map<String, Object> getNewBusinessReport(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Debug.log("getNewBusinessReport == start");
	String ownerUserId = userLogin.getString("userLoginId");
	String warehouseId = (String) context.get("warehouseId");

	String personTypeId = (String) context.get("personTypeId"); // 所属bu
	String createTime_fld0_value = (String) context.get("createTime_fld0_value"); // 开始时间
	String createTime_fld1_value = (String) context.get("createTime_fld1_value"); // 结束时间
	try {
	    List<String> baseIdList = new ArrayList();
	    if (UtilValidate.isEmpty(personTypeId)) {
		personTypeId = "2";
	    }

//	    Map<String, List> map1 = getBuList(ownerUserId, personTypeId);
//	    List<String> partyIdList = map1.get("list");

	    if ("2".equals(personTypeId)) {// 本bu
		String buCode = getBu(delegator, ownerUserId, "N");
		baseIdList.add(buCode);
	    } else if ("allData".equals(personTypeId)) { // 全国
		List<GenericValue> buList = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT"), UtilMisc.toList("sequenceId"), true);
		x: for (GenericValue bu : buList) {
		    String dictionaryCode2 = bu.getString("dictionaryCode2");
		    if ("N".equals(dictionaryCode2)) {
			continue x;
		    }
		    baseIdList.add(bu.getString("dictionaryCode"));
		}

	    } else if ("3".equals(personTypeId)) { // 本大区
		// 先找到人属于那个bu.找到bu属于哪个大区.
		List<GenericValue> shipList = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdTo", ownerUserId), null, true);
		if (UtilValidate.isNotEmpty(shipList)) {
		    // 获取buCode
		    String buCode = EntityUtil.getFirst(shipList).getString("partyIdFrom");
		    List<GenericValue> dataList1 = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("dictionaryCode", buCode), null, true);

		    GenericValue data1 = EntityUtil.getFirst(dataList1);
		    String areaId = data1.getString("parentId");
		    // 获取大区ID
		    if (UtilValidate.isNotEmpty(areaId)) {
			// 获取大区下的bu列表
			List<GenericValue> sunBuList = delegator.findByAnd("DataDictionary",
				UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT", "parentId", areaId), null, true);
			x: for (GenericValue bu : sunBuList) {
			    String dictionaryCode2 = bu.getString("dictionaryCode2");
			    if ("N".equals(dictionaryCode2)) {
				continue x;
			    }
			    baseIdList.add(bu.getString("dictionaryCode"));
			}
		    }

		}
	    } else {
		List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryCode", personTypeId), null, true);
		GenericValue data = EntityUtil.getFirst(dataList);
		String dictionaryTypeId = data.getString("dictionaryTypeId");
		// 各大区
		if (dictionaryTypeId.equals("AREA_DEPARTMENT")) {
		    List<GenericValue> childList = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("parentId", data.getString("dictionaryId")), null, true);
		    for (GenericValue child : childList) {
			String code = child.getString("dictionaryCode");
			baseIdList.add(code);
		    }
		} else {
		    // 各bu
		    baseIdList.add(personTypeId);
		}
	    }

	    Map<String, Object> workMap = FastMap.newInstance();
	    // 单仓销售报告
	    EntityCondition mainCond1 = null;
	    List<EntityCondition> andExprs1 = FastList.newInstance();
	    List<String> idList = CommonUtils.splitCustomStringToList(warehouseId, ",");
	    if (UtilValidate.isNotEmpty(baseIdList)) {
		andExprs1.add(EntityCondition.makeCondition("ownerBuId", EntityOperator.IN, baseIdList));
	    }
	    andExprs1.add(EntityCondition.makeCondition("id", EntityOperator.IN, idList));
	    andExprs1.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "Y"));
	    andExprs1.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    if (andExprs1.size() > 0) {
		mainCond1 = EntityCondition.makeCondition(andExprs1, EntityOperator.AND);
	    }

	    // 按仓库统计 销售情况
	    List dataTableByListWarehouse = new ArrayList();

	    List dataTableByWarehouse = new ArrayList();

	    List orderBy1 = UtilMisc.toList("warehouseCode");
	    List<GenericValue> wmsInventoryList = delegator.findList("CrmWmsInventory", mainCond1, null, orderBy1, null,
		    true);
	    Debug.log("wmsInventoryList == " + wmsInventoryList);
	    for (GenericValue wmsInventory : wmsInventoryList) {
		Map<String, Object> map = FastMap.newInstance();

		String id = wmsInventory.getString("id");
		String warehouseName = wmsInventory.getString("warehouseName");

		map.put("id", id);
		map.put("warehouseName", warehouseName);

		List personList = getBusinessReportAddPersonListRate(delegator, id, createTime_fld0_value,
			createTime_fld1_value);
		map.put("personList", personList);

		dataTableByListWarehouse.add(map);

	    }
	    Debug.log("dataTableByListWarehouse == " + dataTableByListWarehouse);

	    for (int i = 0; i < dataTableByListWarehouse.size(); i++) {
		Map map = (Map) dataTableByListWarehouse.get(i);
		String id = (String) map.get("id");
		String warehouseName = (String) map.get("warehouseName");
		List personList = (List) map.get("personList");
		for (int j = 0; j < personList.size(); j++) {
		    Map warehousePerson = new HashMap();
		    Map personData = (Map) personList.get(j);
		    warehousePerson.putAll(personData);
		    warehousePerson.put("id", id);
		    warehousePerson.put("warehouseName", warehouseName);

		    dataTableByWarehouse.add(warehousePerson);
		}
		dataTableByWarehouse.add(getInventoryDataTotal(id, warehouseName, personList));
	    }

	    workMap.put("dataTableByListWarehouse", dataTableByListWarehouse);
	    workMap.put("dataTableByWarehouse", dataTableByWarehouse);

	    result.put("workMap", workMap);
	    Debug.log("getSalesDataTotalAnalysis == end");
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    public static List customerNewListByProductCategory(Delegator delegator, List<String> baseIdList,
	    String ownerUserId) {
	List result = new ArrayList();
	try {

	    ArrayList<EntityCondition> mainCond = new ArrayList<>();
	    List<String> userList = FastList.newInstance();
	    for (String code : baseIdList) {
		List<GenericValue> itemShipList = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdFrom", code), UtilMisc.toList("-partyIdTo"), true);
		if (UtilValidate.isNotEmpty(itemShipList)) {
		    for (GenericValue item : itemShipList) {
			userList.add(item.getString("partyIdTo"));
		    }
		}
	    }
	    mainCond.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, userList));
	    mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	    List<GenericValue> crmCustomerList;

	    crmCustomerList = delegator.findList("CrmCustomerAndDy",
		    EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, UtilMisc.toList("sequenceId"),
		    null, true);

	    Map map = new HashMap();
	    for (GenericValue crmCustomer : crmCustomerList) {
		String productCategory = crmCustomer.getString("productCategory");
		if (UtilValidate.isEmpty(productCategory)) {
		    continue;
		}
		if (UtilValidate.isEmpty(map.get(productCategory))) {
		    Map productCategoryData = new HashMap();
		    GenericValue gv = delegator.findOne("DataDictionary", true,
			    UtilMisc.toMap("dictionaryId", productCategory));

		    productCategoryData.put("productCategoryName", gv.getString("description"));
		    productCategoryData.put("productCategory", productCategory);
		    productCategoryData.put("sequenceId", gv.getString("sequenceId"));
		    int customerNum = 1;
		    productCategoryData.put("customerNum", customerNum);
		    map.put(productCategory, productCategoryData);
		} else {
		    Map productCategoryData = new HashMap();
		    Map oldProductCategoryData = (Map) map.get(productCategory);
		    productCategoryData.putAll(oldProductCategoryData);
		    int customerNum = (int) oldProductCategoryData.get("customerNum") + 1;
		    Debug.log("customerNum = " + customerNum);
		    productCategoryData.put("customerNum", customerNum);
		    map.put(productCategory, productCategoryData);
		}
	    }
	    Map t = (Map) map.get("PRODUCT_CATEGORY19");
	    map.remove("PRODUCT_CATEGORY19");
	    List mapList = new ArrayList(map.values());
	    Collections.sort(mapList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = ((String) obj1.get("sequenceId")).compareTo((String) obj2.get("sequenceId"));
		    return i;
		}
	    });
	    mapList.add(t);
	    result = mapList;
	} catch (GenericEntityException e) {
	    Debug.log(e.getMessage(), "customerListByProductCategory");
	}
	return result;
    }

    public static Map<String, Object> businessListByNewProductCategory(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Debug.log("businessListByNewProductCategory == start");
	String ownerUserId = userLogin.getString("userLoginId");
	String personTypeId = (String) context.get("personTypeId");
	Timestamp createTime_fld0_value = (Timestamp) context.get("createTime_fld0_value");
	Timestamp createTime_fld1_value = (Timestamp) context.get("createTime_fld1_value");
	if (UtilValidate.isEmpty(createTime_fld0_value)) {
	    createTime_fld0_value = CommonUtils.getLastYear(-2);
	}
	if (UtilValidate.isEmpty(createTime_fld1_value)) {
	    createTime_fld1_value = UtilDateTime.nowTimestamp();
	}
	List<String> baseIdList = new ArrayList();
	try {
	    List ownerUserIdList = new ArrayList();
	    List mainCondUser = new ArrayList();
	    if (UtilValidate.isEmpty(personTypeId))
		personTypeId = "2";

	    List<GenericValue> shipList = delegator.findByAnd("CoRelationship",
		    UtilMisc.toMap("partyIdTo", ownerUserId), null, true);
	    String buCode = "";
	    if (UtilValidate.isNotEmpty(shipList)) {
		buCode = EntityUtil.getFirst(shipList).getString("partyIdFrom");
		if (UtilValidate.isNotEmpty(buCode)) {
		    List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("dictionaryCode", buCode), UtilMisc.toList("sequenceId"), true);
		    GenericValue data = EntityUtil.getFirst(dataList);
		}
	    }

	    if ("2".equals(personTypeId)) {// 本bu
		List<String> users = FastList.newInstance();
		// 本bu下的人员
		List<GenericValue> buShipList = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdFrom", buCode), UtilMisc.toList("-partyIdTo"), true);
		if (UtilValidate.isNotEmpty(buShipList)) {
		    for (GenericValue item : buShipList) {
			String userLoginId1 = item.getString("partyIdTo");
			if (!users.contains(userLoginId1)) {
			    users.add(userLoginId1);
			}
		    }
		}
		users = users.stream().distinct().collect(Collectors.toList());
		ownerUserIdList.addAll(users);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
	    } else if ("allData".equals(personTypeId)) { // 全国
		// ownerUserIdList.add(ownerUserId);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.NOT_EQUAL, "public"));
	    } else if ("3".equals(personTypeId)) { // 本大区
		// 先找到人属于那个bu.找到bu属于哪个大区.
		if (UtilValidate.isNotEmpty(shipList)) {
//		    // 获取buCode
		    List<GenericValue> dataList1 = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("dictionaryCode", buCode), null, true);
		    GenericValue data1 = EntityUtil.getFirst(dataList1);
		    String areaId = data1.getString("parentId");
		    // 获取大区ID
		    if (UtilValidate.isNotEmpty(areaId)) {
			// 获取大区下的bu列表
			List<GenericValue> sunBuList = delegator.findByAnd("DataDictionary",
				UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT", "parentId", areaId), null, true);
			for (GenericValue bu : sunBuList) {
			    List<GenericValue> itemShipList = delegator.findByAnd("CoRelationship",
				    UtilMisc.toMap("partyIdFrom", bu.getString("dictionaryCode")), null, true);
			    for (GenericValue coRelationship : itemShipList) {
				String partyIdTo = coRelationship.getString("partyIdTo");
				ownerUserIdList.add(partyIdTo);
			    }
			}
		    }

		}
		ownerUserIdList.add(ownerUserId);
		mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
	    } else {
		List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryCode", personTypeId), null, true);
		GenericValue data = EntityUtil.getFirst(dataList);
		String dictionaryTypeId = data.getString("dictionaryTypeId");
		// 各大区
		if (dictionaryTypeId.equals("AREA_DEPARTMENT")) {
		    List<GenericValue> childList = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("parentId", data.getString("dictionaryId")), null, true);
		    for (GenericValue child : childList) {
			String code = child.getString("dictionaryCode");
			List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
				UtilMisc.toMap("partyIdFrom", code), null, true);
			for (GenericValue coRelationship : coRelationshipList) {
			    String partyIdTo = coRelationship.getString("partyIdTo");
			    ownerUserIdList.add(partyIdTo);
			}
		    }
		    mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));

		} else {
		    // 各bu
		    List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
			    UtilMisc.toMap("partyIdFrom", personTypeId), null, true);
		    for (GenericValue coRelationship : coRelationshipList) {
			String partyIdTo = coRelationship.getString("partyIdTo");
			ownerUserIdList.add(partyIdTo);
		    }
		    mainCondUser.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
		}
	    }

	    if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
		mainCondUser.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO,
			createTime_fld0_value));
	    }
	    if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
		mainCondUser.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO,
			createTime_fld1_value));
	    }

	    mainCondUser.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    mainCondUser.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "7"));

	    EntityCondition mainCond = EntityCondition.makeCondition(mainCondUser, EntityOperator.AND);

	    List<GenericValue> list = delegator.findList("CrmBusinessItemAndCustomer", mainCond, null,
		    UtilMisc.toList("sequenceId"), null, true);
	    Map map = FastMap.newInstance();
	    for (GenericValue gv : list) {
		String productCategory = gv.getString("productCategory");
		BigDecimal estimatedSalesAmount = gv.getBigDecimal("estimatedSalesAmount");

		if (UtilValidate.isEmpty(estimatedSalesAmount)) {
		    continue;
		}
		if (UtilValidate.isEmpty(productCategory)) {
		    continue;
		}
		BigDecimal followup = new BigDecimal(100);
		if (UtilValidate.isNotEmpty(gv.get("followup"))) {
		    followup = new BigDecimal(gv.getString("followup"));
		}

		estimatedSalesAmount = estimatedSalesAmount.multiply(followup).divide(new BigDecimal(100));

		if (UtilValidate.isEmpty(map.get(productCategory))) {
		    Map productCategoryData = new HashMap();
		    GenericValue dictionaryGv = delegator.findOne("DataDictionary", true,
			    UtilMisc.toMap("dictionaryId", productCategory));

		    productCategoryData.put("productCategoryName", dictionaryGv.getString("description"));
		    productCategoryData.put("productCategory", productCategory);
		    productCategoryData.put("businessNum", estimatedSalesAmount);

		    map.put(productCategory, productCategoryData);
		} else {
		    Map productCategoryData = new HashMap();
		    Map oldProductCategoryData = (Map) map.get(productCategory);
		    productCategoryData.putAll(oldProductCategoryData);
		    BigDecimal businessNum = estimatedSalesAmount
			    .add((BigDecimal) oldProductCategoryData.get("businessNum"));

		    // productCategoryData.put("businessNum", businessNum);
		    productCategoryData.put("businessNum", businessNum);
		    map.put(productCategory, productCategoryData);

		}
	    }

	    Map<String, Object> workMap = FastMap.newInstance();
	    workMap.put("businessListByProductCategory", new ArrayList(map.values()));

	    result.put("workMap", workMap);
	    Debug.log("getBusinessReport == end");
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    public static Map<String, Object> businessListByProductCategory(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Debug.log("businessListByProductCategory == start");
	String ownerUserId = userLogin.getString("userLoginId");
	String dateTypeId = (String) context.get("dateTypeId");
	// 所属bu
	String onlyBu = (String) context.get("onlyBu");
	List<String> baseIdList = new ArrayList();
	List<EntityCondition> andExprs = FastList.newInstance();
	try {
	    if ("Y".equals(onlyBu)) {

		List<GenericValue> coRelationshipInfo = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdTo", ownerUserId, "statusId", "PARTY_ENABLED", "partyRelationshipTypeId",
				"COMPANY_EMPLOYEE"),
			null, true);
		if (UtilValidate.isNotEmpty(coRelationshipInfo)) {

		    GenericValue coRelationshipFrom = EntityUtil.getFirst(coRelationshipInfo);
		    if (UtilValidate.isNotEmpty(coRelationshipInfo)) {
			String partyIdFrom = coRelationshipFrom.getString("partyIdFrom");
			List<GenericValue> coRelationshipList = delegator
				.findByAnd(
					"CoRelationship", UtilMisc.toMap("partyIdFrom", partyIdFrom, "statusId",
						"PARTY_ENABLED", "partyRelationshipTypeId", "COMPANY_EMPLOYEE"),
					null, true);
			for (int i = 0; i < coRelationshipList.size(); i++) {
			    GenericValue coRelationship = coRelationshipList.get(i);
			    String partyIdTo = coRelationship.getString("partyIdTo");
			    baseIdList.add(partyIdTo);
			}
		    }

		}

		andExprs.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, baseIdList));
	    }

//			if (UtilValidate.isNotEmpty(baseIdList)) {
//				andExprs.add(EntityCondition.makeCondition("ownerBuId", EntityOperator.IN, baseIdList));
//			}else {
//				andExprs.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.NOT_EQUAL, "public"));
//
//			}

	    int fromDateNum = -31;
	    if ("month".equals(dateTypeId)) {
		fromDateNum = -31;
	    }
	    if ("quarter".equals(dateTypeId)) {
		fromDateNum = -92;
	    }
	    if ("year".equals(dateTypeId)) {
		fromDateNum = -365;
	    }
	    Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	    Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(fromDateNum));

	    andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "7"));

	    andExprs.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
	    andExprs.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    andExprs.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

//			andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "Y"));

	    EntityCondition mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);

	    List<GenericValue> list = delegator.findList("CrmBusinessItemAndCustomer", mainCond, null,
		    UtilMisc.toList("sequenceId"), null, true);
	    Map map = FastMap.newInstance();
	    for (GenericValue gv : list) {
		String productCategory = gv.getString("productCategory");
		BigDecimal estimatedSalesAmount = gv.getBigDecimal("estimatedSalesAmount");

		if (UtilValidate.isEmpty(estimatedSalesAmount)) {
		    continue;
		}
		if (UtilValidate.isEmpty(productCategory)) {
		    continue;
		}
		BigDecimal followup = new BigDecimal(100);
		if (UtilValidate.isNotEmpty(gv.get("followup"))) {
		    followup = new BigDecimal(gv.getString("followup"));
		}

		estimatedSalesAmount = estimatedSalesAmount.multiply(followup).divide(new BigDecimal(100));

		if (UtilValidate.isEmpty(map.get(productCategory))) {
		    Map productCategoryData = new HashMap();
		    GenericValue dictionaryGv = delegator.findOne("DataDictionary", true,
			    UtilMisc.toMap("dictionaryId", productCategory));

		    productCategoryData.put("productCategoryName", dictionaryGv.getString("description"));
		    productCategoryData.put("productCategory", productCategory);
		    productCategoryData.put("businessNum", estimatedSalesAmount);

//					 		    int businessNum=1;
//					 		   productCategoryData.put("businessNum", businessNum);

		    map.put(productCategory, productCategoryData);
		} else {
		    Map productCategoryData = new HashMap();
		    Map oldProductCategoryData = (Map) map.get(productCategory);
		    productCategoryData.putAll(oldProductCategoryData);
		    BigDecimal businessNum = estimatedSalesAmount
			    .add((BigDecimal) oldProductCategoryData.get("businessNum"));

		    // productCategoryData.put("businessNum", businessNum);
		    productCategoryData.put("businessNum", businessNum);
		    map.put(productCategory, productCategoryData);

		}
	    }
	    Map<String, Object> workMap = FastMap.newInstance();
	    workMap.put("businessListByProductCategory", new ArrayList(map.values()));

	    result.put("workMap", workMap);
	    Debug.log("getBusinessReport == end");
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    public static Map<String, Object> getSaleInventoryByInventoryId(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();

	String inventoryId = (String) context.get("inventoryId");

	try {
	    Map estimatedInventory = getSaleInventory(delegator, inventoryId);
	    BigDecimal estimatedFreeze = (BigDecimal) estimatedInventory.get("estimatedFreeze");
	    BigDecimal estimatedRefrigerate = (BigDecimal) estimatedInventory.get("estimatedRefrigerate");
	    BigDecimal estimatedConstant = (BigDecimal) estimatedInventory.get("estimatedConstant");
	    BigDecimal estimatedNormal = (BigDecimal) estimatedInventory.get("estimatedNormal");
	    result.put("estimatedFreeze", estimatedFreeze);
	    result.put("estimatedRefrigerate", estimatedRefrigerate);
	    result.put("estimatedConstant", estimatedConstant);
	    result.put("estimatedNormal", estimatedNormal);

	    result.put("crmBusinessItemList0Size", estimatedInventory.get("crmBusinessItemList0Size"));
	    result.put("crmBusinessItemList2Size", estimatedInventory.get("crmBusinessItemList2Size"));
	    result.put("crmBusinessItemListSize", estimatedInventory.get("crmBusinessItemListSize"));

	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}

	return result;
    }

    // 获取单个仓库的销售商机数量
    private static Map getSaleInventory(Delegator delegator, String inventoryId) throws Exception {

	Map result = new HashMap();
	List<GenericValue> list = new ArrayList<>();
	BigDecimal estimatedFreezeTotal = BigDecimal.ZERO;
	BigDecimal estimatedRefrigerateTotal = BigDecimal.ZERO;
	BigDecimal estimatedConstantTotal = BigDecimal.ZERO;
	BigDecimal estimatedNormalTotal = BigDecimal.ZERO;

	Debug.log("inventoryId =" + inventoryId);
	// 销售人员 的商机
	ArrayList<EntityCondition> mainCond = new ArrayList<>();
	// mainCond.add(EntityCondition.makeCondition("inventoryId",
	// EntityOperator.EQUALS, inventoryId));
//			   mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "7"));
	mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.IN,
		UtilMisc.toList("0", "1", "2", "3", "4", "5")));

	mainCond.add(EntityCondition.makeCondition("inventoryId", EntityOperator.EQUALS, inventoryId));
	mainCond.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "1"));
	mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	List<GenericValue> crmBusinessItemList = delegator.findList("CrmBusinessItemByStatusId",
		EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);
	list.addAll(crmBusinessItemList);

	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	Timestamp fromDate = WvDatetimeUtils.getPreDay(thruDate, new Long(-31));
	ArrayList<EntityCondition> mainCond2 = new ArrayList<>();
	mainCond2.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "5"));
	mainCond2.add(EntityCondition.makeCondition("inventoryId", EntityOperator.EQUALS, inventoryId));
	mainCond2.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "1"));
	mainCond2.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
	mainCond2.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN, thruDate));
	mainCond2.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	List<GenericValue> crmBusinessItemList2 = delegator.findList("CrmBusinessItemByStatusId",
		EntityCondition.makeCondition(mainCond2, EntityOperator.AND), null, null, null, true);

	result.put("crmBusinessItemList0Size", crmBusinessItemList.size());
	result.put("crmBusinessItemList2Size", crmBusinessItemList2.size());

	list.addAll(crmBusinessItemList2);

	// Debug.log("crmBusinessItemList =" + crmBusinessItemList);
	for (GenericValue crmBusinessItem : list) {
	    String businessId = crmBusinessItem.getString("businessId");
	    String followup = crmBusinessItem.getString("followup");

	    BigDecimal followupBigDecimal = BigDecimal.ZERO;
	    if (UtilValidate.isNotEmpty(followup)) {
		long followupLong = Long.valueOf(followup);
		followupBigDecimal = BigDecimal.valueOf(followupLong).divide(new BigDecimal(100), 2,
			BigDecimal.ROUND_HALF_UP);

	    }

	    // 冷冻
	    BigDecimal estimatedFreezeBigDecimal = BigDecimal.ZERO;
	    BigDecimal estimatedFreeze = crmBusinessItem.getBigDecimal("estimatedFreeze");
	    if (UtilValidate.isNotEmpty(estimatedFreeze)) {
		estimatedFreezeBigDecimal = estimatedFreeze.multiply(followupBigDecimal).setScale(0,
			BigDecimal.ROUND_HALF_UP);
		estimatedFreezeTotal = estimatedFreezeTotal.add(estimatedFreezeBigDecimal);
	    }
	    // 冷藏
	    BigDecimal estimatedRefrigerateBigDecimal = BigDecimal.ZERO;
	    BigDecimal estimatedRefrigerate = crmBusinessItem.getBigDecimal("estimatedRefrigerate");
	    if (UtilValidate.isNotEmpty(estimatedRefrigerate)) {
		estimatedRefrigerateBigDecimal = estimatedRefrigerate.multiply(followupBigDecimal).setScale(0,
			BigDecimal.ROUND_HALF_UP);

		estimatedRefrigerateTotal = estimatedRefrigerateTotal.add(estimatedRefrigerateBigDecimal);
	    }
	    // 恒温
	    BigDecimal estimatedConstantBigDecimal = BigDecimal.ZERO;
	    BigDecimal estimatedConstant = crmBusinessItem.getBigDecimal("estimatedConstant");
	    if (UtilValidate.isNotEmpty(estimatedConstant)) {
		estimatedConstantBigDecimal = estimatedConstant.multiply(followupBigDecimal).setScale(0,
			BigDecimal.ROUND_HALF_UP);

		estimatedConstantTotal = estimatedConstantTotal.add(estimatedConstantBigDecimal);
	    }
	    // 常温
	    BigDecimal estimatedNormalBigDecimal = BigDecimal.ZERO;
	    BigDecimal estimatedNormal = crmBusinessItem.getBigDecimal("estimatedNormal");
	    if (UtilValidate.isNotEmpty(estimatedNormal)) {
		estimatedNormalBigDecimal = estimatedNormal.multiply(followupBigDecimal).setScale(0,
			BigDecimal.ROUND_HALF_UP);

		estimatedNormalTotal = estimatedNormalTotal.add(estimatedNormalBigDecimal);
	    }

	}

	result.put("crmBusinessItemListSize", crmBusinessItemList.size());

	result.put("estimatedFreeze", estimatedFreezeTotal);
	result.put("estimatedRefrigerate", estimatedRefrigerateTotal);
	result.put("estimatedConstant", estimatedConstantTotal);
	result.put("estimatedNormal", estimatedNormalTotal);
	Debug.log("result =" + result);
	return result;

    }

    // 获取单个仓库的销售商机数量
    private static Map getSaleInventoryFromDate2ThruDate(Delegator delegator, String inventoryId, Timestamp fromDate,
	    Timestamp thruDate, String notFollowup) throws Exception {

	Map result = new HashMap();

	BigDecimal estimatedFreezeTotal = BigDecimal.ZERO;
	BigDecimal estimatedRefrigerateTotal = BigDecimal.ZERO;
	BigDecimal estimatedConstantTotal = BigDecimal.ZERO;
	BigDecimal estimatedNormalTotal = BigDecimal.ZERO;

	Debug.log("inventoryId =" + inventoryId);
	// 销售人员 的商机
	ArrayList<EntityCondition> mainCond = new ArrayList<>();

	mainCond.add(
		EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("0", "1", "2", "3", "4")));

	mainCond.add(EntityCondition.makeCondition("inventoryId", EntityOperator.EQUALS, inventoryId));
	mainCond.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "1"));
	mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	if (UtilValidate.isNotEmpty(fromDate)) {
	    mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));

	}
	if (UtilValidate.isNotEmpty(thruDate)) {
	    mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN, thruDate));
	}
	List<GenericValue> crmBusinessItemList = delegator.findList("CrmBusinessItemByStatusId",
		EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);

	// Debug.log("crmBusinessItemList =" + crmBusinessItemList);
	for (GenericValue crmBusinessItem : crmBusinessItemList) {
	    String businessId = crmBusinessItem.getString("businessId");
	    String followup = crmBusinessItem.getString("followup");

	    BigDecimal followupBigDecimal = BigDecimal.ZERO;
	    if (UtilValidate.isNotEmpty(followup)) {
		long followupLong = Long.valueOf(followup);
		followupBigDecimal = BigDecimal.valueOf(followupLong).divide(new BigDecimal(100), 2,
			BigDecimal.ROUND_HALF_UP);

	    }

	    if ("Y".equals(notFollowup)) {
		long followupLong = 100L;
		followupBigDecimal = BigDecimal.valueOf(followupLong).divide(new BigDecimal(100), 2,
			BigDecimal.ROUND_HALF_UP);

	    }

	    Debug.log("businessId =" + businessId);

	    // 冷冻
	    BigDecimal estimatedFreezeBigDecimal = BigDecimal.ZERO;
	    BigDecimal estimatedFreeze = crmBusinessItem.getBigDecimal("estimatedFreeze");
	    if (UtilValidate.isNotEmpty(estimatedFreeze)) {
		estimatedFreezeBigDecimal = estimatedFreeze.multiply(followupBigDecimal).setScale(0,
			BigDecimal.ROUND_HALF_UP);
		estimatedFreezeTotal = estimatedFreezeTotal.add(estimatedFreezeBigDecimal);
	    }
	    // 冷藏
	    BigDecimal estimatedRefrigerateBigDecimal = BigDecimal.ZERO;
	    BigDecimal estimatedRefrigerate = crmBusinessItem.getBigDecimal("estimatedRefrigerate");
	    if (UtilValidate.isNotEmpty(estimatedRefrigerate)) {
		estimatedRefrigerateBigDecimal = estimatedRefrigerate.multiply(followupBigDecimal).setScale(0,
			BigDecimal.ROUND_HALF_UP);

		estimatedRefrigerateTotal = estimatedRefrigerateTotal.add(estimatedRefrigerateBigDecimal);
	    }
	    // 恒温
	    BigDecimal estimatedConstantBigDecimal = BigDecimal.ZERO;
	    BigDecimal estimatedConstant = crmBusinessItem.getBigDecimal("estimatedConstant");
	    if (UtilValidate.isNotEmpty(estimatedConstant)) {
		estimatedConstantBigDecimal = estimatedConstant.multiply(followupBigDecimal).setScale(0,
			BigDecimal.ROUND_HALF_UP);

		estimatedConstantTotal = estimatedConstantTotal.add(estimatedConstantBigDecimal);
	    }
	    // 常温
	    BigDecimal estimatedNormalBigDecimal = BigDecimal.ZERO;
	    BigDecimal estimatedNormal = crmBusinessItem.getBigDecimal("estimatedNormal");
	    if (UtilValidate.isNotEmpty(estimatedNormal)) {
		estimatedNormalBigDecimal = estimatedNormal.multiply(followupBigDecimal).setScale(0,
			BigDecimal.ROUND_HALF_UP);

		estimatedNormalTotal = estimatedNormalTotal.add(estimatedNormalBigDecimal);
	    }

	}

	result.put("crmBusinessItemListSize", crmBusinessItemList.size());

	result.put("estimatedFreeze", estimatedFreezeTotal);
	result.put("estimatedRefrigerate", estimatedRefrigerateTotal);
	result.put("estimatedConstant", estimatedConstantTotal);
	result.put("estimatedNormal", estimatedNormalTotal);
	Debug.log("result =" + result);
	return result;

    }

    /**
     * 商机报告
     */
    public static Map<String, Object> getBusinessReport(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Debug.log("getBusinessReport == start");
	String ownerUserId = userLogin.getString("userLoginId");
	// String buId = (String) context.get("buId");
	// 所属bu
	String onlyBu = (String) context.get("onlyBu");
	List<String> baseIdList = new ArrayList();
	try {
	    if ("Y".equals(onlyBu)) {

		List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdTo", ownerUserId, "statusId", "PARTY_ENABLED", "partyRelationshipTypeId",
				"COMPANY_EMPLOYEE"),
			null, true);
		if (UtilValidate.isNotEmpty(coRelationshipList)) {
		    for (int i = 0; i < coRelationshipList.size(); i++) {
			GenericValue coRelationship = coRelationshipList.get(i);
			String partyIdFrom = coRelationship.getString("partyIdFrom");
			baseIdList.add(partyIdFrom);
		    }
		}

	    }

	    EntityCondition mainCond = null;
	    List<EntityCondition> andExprs = FastList.newInstance();
	    if (UtilValidate.isNotEmpty(baseIdList)) {
		andExprs.add(EntityCondition.makeCondition("ownerBuId", EntityOperator.IN, baseIdList));
	    }
	    andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "Y"));
	    andExprs.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    if (andExprs.size() > 0) {
		mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);
	    }

	    // 按仓库统计 销售情况
	    List salesDataListByWarehouse = new ArrayList();

	    List dataTableByWarehouse = new ArrayList();

	    List orderBy = UtilMisc.toList("warehouseCode");
	    List<GenericValue> wmsInventoryList = delegator.findList("CrmWmsInventory", mainCond, null, orderBy, null,
		    true);

	    for (GenericValue wmsInventory : wmsInventoryList) {
		Map<String, Object> map = FastMap.newInstance();

		String id = wmsInventory.getString("id");
		// String ownerBuId = entity.getString("ownerBuId");
		String warehouseName = wmsInventory.getString("warehouseName");

		map.put("id", id);
		map.put("warehouseName", warehouseName);

		List personList = getBusinessReportAddPersonList(delegator, id, null, null);
		map.put("personList", personList);

		salesDataListByWarehouse.add(map);

	    }

	    for (int i = 0; i < salesDataListByWarehouse.size(); i++) {
		Map map = (Map) salesDataListByWarehouse.get(i);
		String id = (String) map.get("id");
		String warehouseName = (String) map.get("warehouseName");
		List personList = (List) map.get("personList");
		for (int j = 0; j < personList.size(); j++) {
		    Map warehousePerson = new HashMap();
		    Map personData = (Map) personList.get(j);
		    warehousePerson.putAll(personData);
		    warehousePerson.put("id", id);
		    warehousePerson.put("warehouseName", warehouseName);

		    dataTableByWarehouse.add(warehousePerson);
		}
		dataTableByWarehouse.add(getInventoryDataTotal(id, warehouseName, personList));

	    }

	    Map<String, Object> workMap = FastMap.newInstance();

	    workMap.put("salesDataListByWarehouse", salesDataListByWarehouse);
	    workMap.put("dataTableByWarehouse", dataTableByWarehouse);

	    result.put("workMap", workMap);
	    Debug.log("getBusinessReport == end");
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    // 单个仓库的销售额
    private static Map getInventoryDataTotal(String warehouseId, String warehouseName, List<Map> personList) {
	Map inventoryData = new HashMap();
	Integer businessItemNumTotal = 0;
	BigDecimal estimatedSalesAmountTotal = BigDecimal.ZERO;
	BigDecimal estimatedFreezeTotal = BigDecimal.ZERO;
	BigDecimal estimatedRefrigerateTotal = BigDecimal.ZERO;
	BigDecimal estimatedConstantTotal = BigDecimal.ZERO;
	BigDecimal estimatedNormalTotal = BigDecimal.ZERO;

	for (Map oldPersonData : personList) {

	    businessItemNumTotal = businessItemNumTotal + (Integer) oldPersonData.get("businessItemNum");
	    estimatedSalesAmountTotal = estimatedSalesAmountTotal
		    .add((BigDecimal) oldPersonData.get("estimatedSalesAmount"));

	    estimatedFreezeTotal = estimatedFreezeTotal.add((BigDecimal) oldPersonData.get("estimatedFreeze"));
	    estimatedRefrigerateTotal = estimatedRefrigerateTotal
		    .add((BigDecimal) oldPersonData.get("estimatedRefrigerate"));
	    estimatedConstantTotal = estimatedConstantTotal.add((BigDecimal) oldPersonData.get("estimatedConstant"));
	    estimatedNormalTotal = estimatedNormalTotal.add((BigDecimal) oldPersonData.get("estimatedNormal"));

	}
	inventoryData.put("id", warehouseId);
	inventoryData.put("warehouseName", warehouseName);
	inventoryData.put("personName", "小计");
	inventoryData.put("businessItemNum", businessItemNumTotal);
	inventoryData.put("estimatedSalesAmount", estimatedSalesAmountTotal);
	inventoryData.put("estimatedFreeze", estimatedFreezeTotal);
	inventoryData.put("estimatedRefrigerate", estimatedRefrigerateTotal);
	inventoryData.put("estimatedConstant", estimatedConstantTotal);
	inventoryData.put("estimatedNormal", estimatedNormalTotal);

	return inventoryData;
    }

    // 根据仓库id 计算每个人员的销售额
    private static List getBusinessReportAddPersonList(Delegator delegator, String inventoryId, String fromDate,
	    String thruDate) throws Exception {
	List personDataList = new ArrayList();
	Map personDataCollection = new HashMap();
	try {
	    ArrayList<EntityCondition> mainCond = new ArrayList<>();
	    mainCond.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.NOT_EQUAL, "public"));
	    mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "7"));
	    mainCond.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "1"));
	    mainCond.add(EntityCondition.makeCondition("inventoryId", EntityOperator.EQUALS, inventoryId));
	    mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	    if (UtilValidate.isNotEmpty(fromDate)) {
		mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO,
			Timestamp.valueOf(fromDate + " 00:00:00")));
	    }
	    if (UtilValidate.isNotEmpty(thruDate)) {
		mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN,
			Timestamp.valueOf(thruDate + " 23:59:59")));
	    }

	    List<GenericValue> crmBusinessItemList = delegator.findList("CrmBusinessItemByTypeId",
		    EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);

	    for (GenericValue crmBusinessItem : crmBusinessItemList) {
		String ownerUserId = crmBusinessItem.getString("ownerUserId");
		String statusId = crmBusinessItem.getString("statusId");

		// 销售额
		BigDecimal estimatedSalesAmount = BigDecimal.ZERO;
		if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
		    estimatedSalesAmount = crmBusinessItem.getBigDecimal("estimatedSalesAmount");
		}
		// 冷冻
		BigDecimal estimatedFreeze = BigDecimal.ZERO;
		if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedFreeze"))) {
		    estimatedFreeze = crmBusinessItem.getBigDecimal("estimatedFreeze");
		}
		// 冷藏
		BigDecimal estimatedRefrigerate = BigDecimal.ZERO;
		if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedRefrigerate"))) {
		    estimatedRefrigerate = crmBusinessItem.getBigDecimal("estimatedRefrigerate");
		}
		// 恒温
		BigDecimal estimatedConstant = BigDecimal.ZERO;
		if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedConstant"))) {
		    estimatedConstant = crmBusinessItem.getBigDecimal("estimatedConstant");
		}
		// 常温
		BigDecimal estimatedNormal = BigDecimal.ZERO;
		if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedNormal"))) {
		    estimatedNormal = crmBusinessItem.getBigDecimal("estimatedNormal");
		}

		Map personData = new HashMap();
		personData.put("ownerUserId", ownerUserId);
		personData.put("statusId", statusId);
		personData.put("estimatedSalesAmount", estimatedSalesAmount);
		personData.put("estimatedFreeze", estimatedFreeze);
		personData.put("estimatedRefrigerate", estimatedRefrigerate);
		personData.put("estimatedConstant", estimatedConstant);
		personData.put("estimatedNormal", estimatedNormal);
		personData.put("businessItemNum", 1);

		personDataCollection = addPersonDataCollectionEstimatedNum(delegator, personDataCollection, personData);
	    }

	    personDataList = new ArrayList<Map>(personDataCollection.values());
	    // personDataList.add(inventoryData);

	    // 按照商机数量进行排序
	    Collections.sort(personDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    // int i =
		    // ((Integer)obj1.get("businessNum")).compareTo((Integer)obj2.get("businessNum"));//正序
		    int i = ((Integer) obj2.get("businessItemNum")).compareTo((Integer) obj1.get("businessItemNum"));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}

	Debug.log("personDataList =" + personDataList);
	return personDataList;

    }

//处理   将此页的逻辑修改为：“入仓/签约/失败”仍旧选取，只是这三类的加权计算的权重为0。
    private static List getBusinessReportAddPersonListRate(Delegator delegator, String inventoryId, String fromDate,
	    String thruDate) throws Exception {
	List personDataList = new ArrayList();
	Map personDataCollection = new HashMap();
	try {
	    ArrayList<EntityCondition> mainCond = new ArrayList<>();
	    mainCond.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.NOT_EQUAL, "public"));
//	    mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.IN,
//		    UtilMisc.toList("0", "1", "2", "3", "4")));

	    mainCond.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "1"));
	    mainCond.add(EntityCondition.makeCondition("inventoryId", EntityOperator.EQUALS, inventoryId));
	    mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	    if (UtilValidate.isNotEmpty(fromDate)) {
		mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO,
			Timestamp.valueOf(fromDate + " 00:00:00")));
	    }
	    if (UtilValidate.isNotEmpty(thruDate)) {
		mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN,
			Timestamp.valueOf(thruDate + " 23:59:59")));
	    }

	    List<GenericValue> crmBusinessItemList = delegator.findList("CrmBusinessItemByTypeId",
		    EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);

	    for (GenericValue crmBusinessItem : crmBusinessItemList) {
		String ownerUserId = crmBusinessItem.getString("ownerUserId");
		String statusId = crmBusinessItem.getString("statusId");
		String followup = crmBusinessItem.getString("followup");

		BigDecimal followupBigDecimal = BigDecimal.ZERO;
		if (UtilValidate.isNotEmpty(followup)) {
		    long followupLong = Long.valueOf(followup);
		    followupBigDecimal = BigDecimal.valueOf(followupLong).divide(new BigDecimal(100), 2,
			    BigDecimal.ROUND_HALF_UP);
		}
		if (("5".equals(statusId)) || ("7".equals(statusId))) {
		    followupBigDecimal = BigDecimal.ZERO;
		}

		// 销售额
		BigDecimal estimatedSalesAmount = BigDecimal.ZERO;
		if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
		    estimatedSalesAmount = crmBusinessItem.getBigDecimal("estimatedSalesAmount");
		}
		// 冷冻
		BigDecimal estimatedFreeze = BigDecimal.ZERO;
		if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedFreeze"))) {
		    estimatedFreeze = crmBusinessItem.getBigDecimal("estimatedFreeze");
		    // 根据百分比再计算
		    estimatedFreeze = estimatedFreeze.multiply(followupBigDecimal).setScale(0,
			    BigDecimal.ROUND_HALF_UP);

		}
		// 冷藏
		BigDecimal estimatedRefrigerate = BigDecimal.ZERO;
		if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedRefrigerate"))) {
		    estimatedRefrigerate = crmBusinessItem.getBigDecimal("estimatedRefrigerate");
		    estimatedRefrigerate = estimatedRefrigerate.multiply(followupBigDecimal).setScale(0,
			    BigDecimal.ROUND_HALF_UP);
		}
		// 恒温
		BigDecimal estimatedConstant = BigDecimal.ZERO;
		if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedConstant"))) {
		    estimatedConstant = crmBusinessItem.getBigDecimal("estimatedConstant");
		    estimatedConstant = estimatedConstant.multiply(followupBigDecimal).setScale(0,
			    BigDecimal.ROUND_HALF_UP);
		}
		// 常温
		BigDecimal estimatedNormal = BigDecimal.ZERO;
		if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedNormal"))) {
		    estimatedNormal = crmBusinessItem.getBigDecimal("estimatedNormal");
		    estimatedNormal = estimatedNormal.multiply(followupBigDecimal).setScale(0,
			    BigDecimal.ROUND_HALF_UP);
		}

		Map personData = new HashMap();
		personData.put("ownerUserId", ownerUserId);
		personData.put("statusId", statusId);
		personData.put("estimatedSalesAmount", estimatedSalesAmount);
		personData.put("estimatedFreeze", estimatedFreeze);
		personData.put("estimatedRefrigerate", estimatedRefrigerate);
		personData.put("estimatedConstant", estimatedConstant);
		personData.put("estimatedNormal", estimatedNormal);
		personData.put("businessItemNum", 1);

		personDataCollection = addPersonDataCollectionEstimatedNum(delegator, personDataCollection, personData);

	    }

	    personDataList = new ArrayList<Map>(personDataCollection.values());
	    // personDataList.add(inventoryData);

	    // 按照商机数量进行排序
	    Collections.sort(personDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    // int i =
		    // ((Integer)obj1.get("businessNum")).compareTo((Integer)obj2.get("businessNum"));//正序
		    int i = ((Integer) obj2.get("businessItemNum")).compareTo((Integer) obj1.get("businessItemNum"));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}

	return personDataList;

    }

    // 个人累加数据
    private static Map addPersonDataCollectionEstimatedNum(Delegator delegator, Map personDataCollection,
	    Map newPersonData) throws GenericEntityException {
	Map result = personDataCollection;
	String newOwnerUserId = (String) newPersonData.get("ownerUserId");
	String newStatusId = (String) newPersonData.get("statusId");
	BigDecimal newEstimatedSalesAmount = (BigDecimal) newPersonData.get("estimatedSalesAmount");

	// 冷冻
	BigDecimal newEstimatedFreeze = (BigDecimal) newPersonData.get("estimatedFreeze");
	// 冷藏
	BigDecimal newEstimatedRefrigerate = (BigDecimal) newPersonData.get("estimatedRefrigerate");
	// 恒温
	BigDecimal newEstimatedConstant = (BigDecimal) newPersonData.get("estimatedConstant");
	// 常温
	BigDecimal newEstimatedNormal = (BigDecimal) newPersonData.get("estimatedNormal");

	Integer newBusinessItemNum = (Integer) newPersonData.get("businessItemNum");

	Map personData = new HashMap();

	if (UtilValidate.isEmpty(personDataCollection.get(newOwnerUserId))) {

	    String personName = getPersonName(delegator, newOwnerUserId);
	    String buName = getBuNameByUserLoginId(delegator, newOwnerUserId);
	    personData.put("personName", personName);
	    personData.put("buName", buName);
	    personData.put("ownerUserId", newOwnerUserId);
	    // personData.put("businessNum", 1);
	    personData.put("businessItemNum", newBusinessItemNum);
	    personData.put("estimatedSalesAmount", newEstimatedSalesAmount);
	    personData.put("estimatedFreeze", newEstimatedFreeze);
	    personData.put("estimatedRefrigerate", newEstimatedRefrigerate);
	    personData.put("estimatedConstant", newEstimatedConstant);
	    personData.put("estimatedNormal", newEstimatedNormal);

	} else {
	    Map oldPersonData = (Map) personDataCollection.get(newOwnerUserId);
	    personData.putAll(oldPersonData);
	    Integer businessItemNum = newBusinessItemNum + (Integer) oldPersonData.get("businessItemNum");
	    personData.put("businessItemNum", businessItemNum);
	    BigDecimal estimatedSalesAmount = newEstimatedSalesAmount
		    .add((BigDecimal) oldPersonData.get("estimatedSalesAmount"));
	    personData.put("estimatedSalesAmount", estimatedSalesAmount);

	    BigDecimal estimatedFreeze = newEstimatedFreeze.add((BigDecimal) oldPersonData.get("estimatedFreeze"));
	    personData.put("estimatedFreeze", estimatedFreeze);
	    BigDecimal estimatedRefrigerate = newEstimatedRefrigerate
		    .add((BigDecimal) oldPersonData.get("estimatedRefrigerate"));
	    personData.put("estimatedRefrigerate", estimatedRefrigerate);
	    BigDecimal estimatedConstant = newEstimatedConstant
		    .add((BigDecimal) oldPersonData.get("estimatedConstant"));
	    personData.put("estimatedConstant", estimatedConstant);
	    BigDecimal estimatedNormal = newEstimatedNormal.add((BigDecimal) oldPersonData.get("estimatedNormal"));
	    personData.put("estimatedNormal", estimatedNormal);

	}

	result.put(newOwnerUserId, personData);

	return result;

    }

    /**
     * 客户排行榜
     *
     * @param dctx
     * @param context
     * @return
     */
    public static Map<String, Object> crmCustomerRanking(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();
	Map<String, Object> workMap = new HashMap<>();

	Map personDataCollection = new HashMap();
	Map buDataCollection = new HashMap();
	List<Map> personDataList = new ArrayList();
	List<Map> buDataList = new ArrayList();

	try {
	    ArrayList<EntityCondition> mainCond = new ArrayList<>();
	    mainCond.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.NOT_EQUAL, "public"));
	    mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	    List<GenericValue> crmCustomerList = delegator.findList("CrmCustomer",
		    EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);

	    for (GenericValue crmCustomer : crmCustomerList) {

		String ownerUserId = crmCustomer.getString("ownerUserId");

		Map personData = new HashMap();
		personData.put("ownerUserId", ownerUserId);

		personDataCollection = addPersonDataCollectionCustomer(delegator, personDataCollection, personData);
		buDataCollection = addBuDataCollectionCustomer(delegator, buDataCollection, personData);
	    }

	    personDataList = new ArrayList<Map>(personDataCollection.values());
	    buDataList = new ArrayList<Map>(buDataCollection.values());

	    // 按照客户数量进行排序
	    Collections.sort(personDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = ((Integer) obj2.get("customerNum")).compareTo((Integer) obj1.get("customerNum"));// 倒序
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    // 按照客户数量进行排序
	    Collections.sort(buDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = ((Integer) obj2.get("customerNum")).compareTo((Integer) obj1.get("customerNum"));// 倒序
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    int personDataTotalCustomerNum = 0;
	    for (Map personData : personDataList) {
		personDataTotalCustomerNum = personDataTotalCustomerNum + (int) personData.get("customerNum");
	    }
	    Map personData2 = new HashMap();
	    personData2.put("rank", "汇总");
	    personData2.put("customerNum", personDataTotalCustomerNum);
	    personDataList.add(personData2);

	    int buDataTotalCustomerNum = 0;
	    for (Map personData : buDataList) {
		buDataTotalCustomerNum = buDataTotalCustomerNum + (int) personData.get("customerNum");
	    }
	    Map buData2 = new HashMap();
	    buData2.put("rank", "汇总");
	    buData2.put("customerNum", buDataTotalCustomerNum);

	    buDataList.add(buData2);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	workMap.put("personDataList", personDataList);
	workMap.put("buDataList", buDataList);
	result.put("workMap", workMap);
	return result;
    }

    public static Map<String, Object> crmBusinessCustRankingOld(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();
	Map<String, Object> workMap = new HashMap<>();
//	String dateTypeId = (String) context.get("dateTypeId");
//	Timestamp createTime_fld0_value = (Timestamp) context.get("createTime_fld0_value");
//	Timestamp createTime_fld1_value = (Timestamp) context.get("createTime_fld1_value");

	Map personDataCollection = new HashMap();
	Map buDataCollection = new HashMap();
	List<Map> personDataList = new ArrayList();
	List<Map> buDataList = new ArrayList();

	Map invDataCollection = new HashMap();
	List<Map> invDataList = new ArrayList();

	int fromDateNum = -90;
//	if ("1".equals(dateTypeId)) {
//	    fromDateNum = -1;
//	}
//	if ("2".equals(dateTypeId)) {
//	    fromDateNum = -7;
//	}
//	if ("3".equals(dateTypeId)) {
//	    fromDateNum = -31;
//	}
//
//	if ("4".equals(dateTypeId)) {
//	    fromDateNum = -365;
//	}
	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(fromDateNum));
	try {
	    ArrayList<EntityCondition> mainCond = new ArrayList<>();
	    mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_IN, UtilMisc.toList("5", "7")));
	    mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
//	    if ("5".equals(dateTypeId)) {
//		// 如果存在时间选择
//		if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
//		    mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO,
//			    createTime_fld0_value));
//		}
//		if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
//		    mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO,
//			    createTime_fld1_value));
//		}
//	    } else {
	    mainCond.add(EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
//	    }

	    EntityCondition mainCond2 = null;
	    List<EntityCondition> andExprs = FastList.newInstance();

	    andExprs.add(EntityCondition.makeCondition("whouseId", EntityOperator.NOT_EQUAL, "_NA_"));
	    andExprs.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "1"));
	    andExprs.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	    andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_IN, UtilMisc.toList("5", "7")));

//	    if ("5".equals(dateTypeId)) {
//		// 如果存在时间选择
//		if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
//		    andExprs.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO,
//			    createTime_fld0_value));
//		}
//		if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
//		    andExprs.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO,
//			    createTime_fld1_value));
//		}
//	    } else {
	    andExprs.add(EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		andExprs.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
//	    }
	    if (andExprs.size() > 0) {
		mainCond2 = EntityCondition.makeCondition(andExprs, EntityOperator.AND);
	    }
	    List<GenericValue> itemList = delegator.findList("CrmBusinessItemBuByTypeId2", mainCond2, null,
		    UtilMisc.toList("-status5Time"), null, true);

	    List<Map<String, Object>> whouseList = FastList.newInstance();
	    for (GenericValue item : itemList) {
		String whouseId = item.getString("whouseId");
		String warehouseName = item.getString("warehouseName");
		String warehouseCode = item.getString("warehouseCode");
		if (UtilValidate.isEmpty(warehouseCode))
		    warehouseCode = "100000";
		Map map1 = UtilMisc.toMap("whouseId", whouseId, "warehouseCode", warehouseCode, "warehouseName",
			warehouseName);
		if (!whouseList.contains(map1)) {
		    whouseList.add(map1);
		}
	    }
	    List mainCond1 = new ArrayList();
	    mainCond1.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	    mainCond1.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "Y"));

	    List<GenericValue> invList = delegator.findList("CrmWmsInventory",
		    EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null, UtilMisc.toList("-createTime"),
		    null, true);

	    // 去除已删除的仓库
	    List<Map<String, Object>> delWhouseList = FastList.newInstance();
	    for (Map<String, Object> whouse : whouseList) {
		String whouseId1 = (String) whouse.get("whouseId");
		boolean isOk = false;
		for (GenericValue inv : invList) {
		    String whouseId = inv.getString("id");
		    if (whouseId1.equals(whouseId)) {
			isOk = true;
		    }
		}
		if (isOk == false) {
		    delWhouseList.add(whouse);
		}
	    }

	    whouseList.removeAll(delWhouseList);
	    Collections.sort(whouseList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = ((String) obj1.get("warehouseCode")).compareTo((String) obj2.get("warehouseCode"));
		    return i;
		}
	    });

	    List<String> buList = FastList.newInstance();
	    Map<String, Map<String, Object>> buMap = FastMap.newInstance();
	    // 仓库
	    for (Map<String, Object> whouse : whouseList) {
		String whouseId1 = (String) whouse.get("whouseId");
		String warehouseName1 = (String) whouse.get("warehouseName");

		if (!buList.contains(whouseId1)) {
		    buList.add(whouseId1);
		    Map<String, Object> infoMap = FastMap.newInstance();
		    infoMap.put("whouseId", whouseId1);
		    infoMap.put("warehouseName", warehouseName1);
		    infoMap.put("estimatedSalesAmount", BigDecimal.ZERO);
		    buMap.put(whouseId1, infoMap);
		} else {
		    Map<String, Object> infoMap = buMap.get(whouseId1);
		    BigDecimal oldAmount = (BigDecimal) infoMap.get("estimatedSalesAmount");
		    if (UtilValidate.isEmpty(oldAmount))
			oldAmount = BigDecimal.ZERO;
		    infoMap.put("estimatedSalesAmount", oldAmount);
		    buMap.put(whouseId1, infoMap);
		}

		for (Map item : itemList) {
		    String whouseId = (String) item.get("whouseId");
		    BigDecimal itemAount1 = (BigDecimal) item.get("estimatedSalesAmount");
		    if (UtilValidate.isEmpty(itemAount1)) {
			itemAount1 = BigDecimal.ZERO;
		    }
		    if (whouseId1.equals(whouseId)) {
			Map<String, Object> infoMap = buMap.get(whouseId);
			BigDecimal oldAmount = (BigDecimal) infoMap.get("estimatedSalesAmount");
			if (UtilValidate.isEmpty(oldAmount))
			    oldAmount = BigDecimal.ZERO;
			oldAmount = oldAmount.add(itemAount1);
			infoMap.put("estimatedSalesAmount", oldAmount);
			buMap.put(whouseId, infoMap);
		    }
		}
	    }

	    for (String m : buMap.keySet()) {
		invDataList.add(buMap.get(m));
	    }

	    // 按照商机金额进行排序
	    Collections.sort(invDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = Integer.valueOf((int) ((BigDecimal) obj2.get("estimatedSalesAmount")).doubleValue())
			    .compareTo(Integer
				    .valueOf((int) ((BigDecimal) obj1.get("estimatedSalesAmount")).doubleValue()));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });
	    workMap.put("invDataList", invDataList);

	    List<GenericValue> crmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);

	    for (GenericValue crmBusiness : crmBusinessList) {

		String businessId = crmBusiness.getString("id");
		String ownerUserId = crmBusiness.getString("ownerUserId");
		if ("public".equals(ownerUserId)) {
		    continue;
		}
		Map param = UtilMisc.toMap("businessId", businessId);

		List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null, true);

		BigDecimal totalEstimatedSalesAmount = BigDecimal.ZERO;
		for (GenericValue crmBusinessItem : crmBusinessItemList) {
		    if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
			BigDecimal estimatedSalesAmount = crmBusinessItem.getBigDecimal("estimatedSalesAmount");
			totalEstimatedSalesAmount = totalEstimatedSalesAmount.add(estimatedSalesAmount);
		    }
		}
		Map personData = new HashMap();
		personData.put("ownerUserId", ownerUserId);
		personData.put("estimatedSalesAmount", totalEstimatedSalesAmount);
		// Debug.log("personDataCollection = " + personDataCollection);
		// Debug.log("personData = " + personData);
		if (crmBusinessItemList.size() > 0) {
		    personDataCollection = addPersonDataCollectionBusinessNum1(delegator, personDataCollection,
			    personData);
		    // Debug.log("buDataCollection = " + buDataCollection);

		    buDataCollection = addBuDataCollectionBusinessNum1(delegator, buDataCollection, personData);

		    invDataCollection = addBuDataCollectionBusinessNum1(delegator, buDataCollection, personData);
		}
	    }

	    personDataList = new ArrayList<Map>(personDataCollection.values());
	    buDataList = new ArrayList<Map>(buDataCollection.values());
	    // 按照商机金额进行排序
	    Collections.sort(personDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = Integer.valueOf((int) ((BigDecimal) obj2.get("estimatedSalesAmount")).doubleValue())
			    .compareTo(Integer
				    .valueOf((int) ((BigDecimal) obj1.get("estimatedSalesAmount")).doubleValue()));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    // 按照商机金额进行排序
	    Collections.sort(buDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = Integer.valueOf((int) ((BigDecimal) obj2.get("estimatedSalesAmount")).doubleValue())
			    .compareTo(Integer
				    .valueOf((int) ((BigDecimal) obj1.get("estimatedSalesAmount")).doubleValue()));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    List<Map> personNewDataList = new ArrayList();
	    for (Map personData : personDataList) {
		Map personData2 = new HashMap();
		personData2.put("buName", personData.get("buName"));
		personData2.put("ownerUserId", personData.get("ownerUserId"));
		personData2.put("personName", personData.get("personName"));
		personData2.put("estimatedSalesAmount", personData.get("estimatedSalesAmount"));
		personNewDataList.add(personData2);
	    }
	    List<Map> buDataNewList = new ArrayList();
	    for (Map buData : buDataList) {
		Map buData2 = new HashMap();
		buData2.put("buName", buData.get("buName"));
		buData2.put("buId", buData.get("buId"));
		buData2.put("estimatedSalesAmount", buData.get("estimatedSalesAmount"));
		buDataNewList.add(buData2);
	    }
	    // Debug.log("buDataList = " + buDataNewList);
	    workMap.put("personDataList", personNewDataList);
	    workMap.put("buDataList", buDataNewList);
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	result.put("workMap", workMap);
	Debug.log("workMap ===" + workMap);
	return result;
    }

    public static Map<String, Object> crmBusinessCustRanking(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();
	Map<String, Object> workMap = new HashMap<>();
//    	String dateTypeId = (String) context.get("dateTypeId");
	Timestamp createTime_fld0_value = (Timestamp) context.get("createTime_fld0_value");
	Timestamp createTime_fld1_value = (Timestamp) context.get("createTime_fld1_value");

	Map personDataCollection = new HashMap();
	Map buDataCollection = new HashMap();
	List<Map> personDataList = new ArrayList();
	List<Map> buDataList = new ArrayList();

	Map invDataCollection = new HashMap();
	List<Map> invDataList = new ArrayList();

	int fromDateNum = -90;
	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(fromDateNum));

	if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
	    fromDate = createTime_fld0_value;
	}
	if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
	    thruDate = createTime_fld1_value;
	}

	try {
	    ArrayList<EntityCondition> mainCond = new ArrayList<>();
	    mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_IN, UtilMisc.toList("5", "7")));
	    mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

//    		mainCond.add(
//    			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));

	    mainCond.add(EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
	    mainCond.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN, thruDate));

	    EntityCondition mainCond2 = null;
	    List<EntityCondition> andExprs = FastList.newInstance();

	    andExprs.add(EntityCondition.makeCondition("whouseId", EntityOperator.NOT_EQUAL, "_NA_"));
	    andExprs.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "1"));
	    andExprs.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	    andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_IN, UtilMisc.toList("5", "7")));

//    		andExprs.add(
//    			EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));

	    andExprs.add(EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
	    andExprs.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN, thruDate));

	    if (andExprs.size() > 0) {
		mainCond2 = EntityCondition.makeCondition(andExprs, EntityOperator.AND);
	    }
	    List<GenericValue> itemList = delegator.findList("CrmBusinessItemBuByTypeId2", mainCond2, null,
		    UtilMisc.toList("-status5Time"), null, true);

	    List<Map<String, Object>> whouseList = FastList.newInstance();
	    for (GenericValue item : itemList) {
		String whouseId = item.getString("whouseId");
		String warehouseName = item.getString("warehouseName");
		String warehouseCode = item.getString("warehouseCode");
		if (UtilValidate.isEmpty(warehouseCode))
		    warehouseCode = "100000";
		Map map1 = UtilMisc.toMap("whouseId", whouseId, "warehouseCode", warehouseCode, "warehouseName",
			warehouseName);
		if (!whouseList.contains(map1)) {
		    whouseList.add(map1);
		}
	    }
	    List mainCond1 = new ArrayList();
	    mainCond1.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	    mainCond1.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "Y"));

	    List<GenericValue> invList = delegator.findList("CrmWmsInventory",
		    EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null, UtilMisc.toList("-createTime"),
		    null, true);

	    // 去除已删除的仓库
	    List<Map<String, Object>> delWhouseList = FastList.newInstance();
	    for (Map<String, Object> whouse : whouseList) {
		String whouseId1 = (String) whouse.get("whouseId");
		boolean isOk = false;
		for (GenericValue inv : invList) {
		    String whouseId = inv.getString("id");
		    if (whouseId1.equals(whouseId)) {
			isOk = true;
		    }
		}
		if (isOk == false) {
		    delWhouseList.add(whouse);
		}
	    }

	    whouseList.removeAll(delWhouseList);
	    Collections.sort(whouseList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = ((String) obj1.get("warehouseCode")).compareTo((String) obj2.get("warehouseCode"));
		    return i;
		}
	    });

	    List<String> buList = FastList.newInstance();
	    Map<String, Map<String, Object>> buMap = FastMap.newInstance();
	    // 仓库
	    for (Map<String, Object> whouse : whouseList) {
		String whouseId1 = (String) whouse.get("whouseId");
		String warehouseName1 = (String) whouse.get("warehouseName");

		if (!buList.contains(whouseId1)) {
		    buList.add(whouseId1);
		    Map<String, Object> infoMap = FastMap.newInstance();
		    infoMap.put("whouseId", whouseId1);
		    infoMap.put("warehouseName", warehouseName1);
		    infoMap.put("estimatedSalesAmount", BigDecimal.ZERO);
		    buMap.put(whouseId1, infoMap);
		} else {
		    Map<String, Object> infoMap = buMap.get(whouseId1);
		    BigDecimal oldAmount = (BigDecimal) infoMap.get("estimatedSalesAmount");
		    if (UtilValidate.isEmpty(oldAmount))
			oldAmount = BigDecimal.ZERO;
		    infoMap.put("estimatedSalesAmount", oldAmount);
		    buMap.put(whouseId1, infoMap);
		}

		for (Map item : itemList) {
		    String whouseId = (String) item.get("whouseId");
		    BigDecimal itemAount1 = (BigDecimal) item.get("estimatedSalesAmount");
		    if (UtilValidate.isEmpty(itemAount1)) {
			itemAount1 = BigDecimal.ZERO;
		    }
		    if (whouseId1.equals(whouseId)) {
			Map<String, Object> infoMap = buMap.get(whouseId);
			BigDecimal oldAmount = (BigDecimal) infoMap.get("estimatedSalesAmount");
			if (UtilValidate.isEmpty(oldAmount))
			    oldAmount = BigDecimal.ZERO;
			oldAmount = oldAmount.add(itemAount1);
			infoMap.put("estimatedSalesAmount", oldAmount);
			buMap.put(whouseId, infoMap);
		    }
		}
	    }

	    for (String m : buMap.keySet()) {
		invDataList.add(buMap.get(m));
	    }

	    // 按照商机金额进行排序
	    Collections.sort(invDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = Integer.valueOf((int) ((BigDecimal) obj2.get("estimatedSalesAmount")).doubleValue())
			    .compareTo(Integer
				    .valueOf((int) ((BigDecimal) obj1.get("estimatedSalesAmount")).doubleValue()));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });
	    workMap.put("invDataList", invDataList);

	    List<GenericValue> crmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);

	    for (GenericValue crmBusiness : crmBusinessList) {

		String businessId = crmBusiness.getString("id");
		String ownerUserId = crmBusiness.getString("ownerUserId");
		if ("public".equals(ownerUserId)) {
		    continue;
		}
		Map param = UtilMisc.toMap("businessId", businessId);

		List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null, true);

		BigDecimal totalEstimatedSalesAmount = BigDecimal.ZERO;
		for (GenericValue crmBusinessItem : crmBusinessItemList) {
		    if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
			BigDecimal estimatedSalesAmount = crmBusinessItem.getBigDecimal("estimatedSalesAmount");
			totalEstimatedSalesAmount = totalEstimatedSalesAmount.add(estimatedSalesAmount);
		    }
		}
		Map personData = new HashMap();
		personData.put("ownerUserId", ownerUserId);
		personData.put("estimatedSalesAmount", totalEstimatedSalesAmount);
		// Debug.log("personDataCollection = " + personDataCollection);
		// Debug.log("personData = " + personData);
		if (crmBusinessItemList.size() > 0) {
		    personDataCollection = addPersonDataCollectionBusinessNum1(delegator, personDataCollection,
			    personData);
		    // Debug.log("buDataCollection = " + buDataCollection);

		    buDataCollection = addBuDataCollectionBusinessNum1(delegator, buDataCollection, personData);

		    invDataCollection = addBuDataCollectionBusinessNum1(delegator, buDataCollection, personData);
		}
	    }

	    personDataList = new ArrayList<Map>(personDataCollection.values());
	    buDataList = new ArrayList<Map>(buDataCollection.values());
	    // 按照商机金额进行排序
	    Collections.sort(personDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = Integer.valueOf((int) ((BigDecimal) obj2.get("estimatedSalesAmount")).doubleValue())
			    .compareTo(Integer
				    .valueOf((int) ((BigDecimal) obj1.get("estimatedSalesAmount")).doubleValue()));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    // 按照商机金额进行排序
	    Collections.sort(buDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = Integer.valueOf((int) ((BigDecimal) obj2.get("estimatedSalesAmount")).doubleValue())
			    .compareTo(Integer
				    .valueOf((int) ((BigDecimal) obj1.get("estimatedSalesAmount")).doubleValue()));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    List<Map> personNewDataList = new ArrayList();
	    for (Map personData : personDataList) {
		Map personData2 = new HashMap();
		personData2.put("buName", personData.get("buName"));
		personData2.put("ownerUserId", personData.get("ownerUserId"));
		personData2.put("personName", personData.get("personName"));
		personData2.put("estimatedSalesAmount", personData.get("estimatedSalesAmount"));
		personNewDataList.add(personData2);
	    }
	    List<Map> buDataNewList = new ArrayList();
	    for (Map buData : buDataList) {
		Map buData2 = new HashMap();
		buData2.put("buName", buData.get("buName"));
		buData2.put("buId", buData.get("buId"));
		buData2.put("estimatedSalesAmount", buData.get("estimatedSalesAmount"));
		buDataNewList.add(buData2);
	    }
	    // Debug.log("buDataList = " + buDataNewList);
	    workMap.put("personDataList", personNewDataList);
	    workMap.put("buDataList", buDataNewList);
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	result.put("workMap", workMap);
	Debug.log("workMap ===" + workMap);
	return result;
    }

    /**
     * 商机排行榜
     *
     * @param dctx
     * @param context
     * @return
     */
    public static Map<String, Object> crmBusinessRanking(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();
	Map<String, Object> workMap = new HashMap<>();
	String dateTypeId = (String) context.get("dateTypeId");
	String typeId = (String) context.get("typeId");
	Timestamp createTime_fld0_value = (Timestamp) context.get("createTime_fld0_value");
	Timestamp createTime_fld1_value = (Timestamp) context.get("createTime_fld1_value");

	Map personDataCollection = new HashMap();
	Map buDataCollection = new HashMap();
	List<Map> personDataList = new ArrayList();

	List<Map> buDataList = new ArrayList();

	int fromDateNum = -31;
	if ("month".equals(dateTypeId)) {
	    fromDateNum = -31;
	}
	if ("quarter".equals(dateTypeId)) {
	    fromDateNum = -92;
	}
	if ("year".equals(dateTypeId)) {
	    fromDateNum = -365;
	}
	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(fromDateNum));

	if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
	    fromDate = createTime_fld0_value;
	}
	if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
	    thruDate = createTime_fld1_value;
	}
	try {

	    ArrayList<EntityCondition> mainCond = new ArrayList<>();
	    mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "7"));

	    mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
	    mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
	    mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    List<GenericValue> crmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);
	    for (GenericValue crmBusiness : crmBusinessList) {

		String businessId = crmBusiness.getString("id");
		String ownerUserId = crmBusiness.getString("ownerUserId");
		if ("public".equals(ownerUserId)) {
		    continue;
		}

		String statusId = crmBusiness.getString("statusId");

		Map param = UtilMisc.toMap("businessId", businessId);
		if (UtilValidate.isNotEmpty(typeId)) {
		    param.put("typeId", typeId);
		}
		List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null, true);

		BigDecimal totalEstimatedSalesAmount = BigDecimal.ZERO;
		int businessItemNum = 0;
		for (GenericValue crmBusinessItem : crmBusinessItemList) {
		    if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
			BigDecimal estimatedSalesAmount = crmBusinessItem.getBigDecimal("estimatedSalesAmount");
			totalEstimatedSalesAmount = totalEstimatedSalesAmount.add(estimatedSalesAmount);
		    }
		}
		Map personData = new HashMap();
		personData.put("ownerUserId", ownerUserId);
		personData.put("statusId", statusId);
		personData.put("estimatedSalesAmount", totalEstimatedSalesAmount);
		personData.put("businessItemNum", crmBusinessItemList.size());
		if (crmBusinessItemList.size() > 0) {
		    personDataCollection = addPersonDataCollectionBusinessNum(delegator, personDataCollection,
			    personData);
		    buDataCollection = addBuDataCollectionBusinessNum(delegator, buDataCollection, personData);
		}

	    }

	    personDataList = new ArrayList<Map>(personDataCollection.values());
	    buDataList = new ArrayList<Map>(buDataCollection.values());

	    // 按照商机数量进行排序
	    Collections.sort(personDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    // int i =
		    // ((Integer)obj1.get("businessNum")).compareTo((Integer)obj2.get("businessNum"));//正序
		    int i = ((Integer) obj2.get("businessNum")).compareTo((Integer) obj1.get("businessNum"));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    // 按照商机数量进行排序
	    Collections.sort(buDataList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    // int i =
		    // ((Integer)obj1.get("businessNum")).compareTo((Integer)obj2.get("businessNum"));
		    // //正序
		    int i = ((Integer) obj2.get("businessNum")).compareTo((Integer) obj1.get("businessNum"));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    int personDataTotalBusinessNum = 0;
	    int personDataTotalBusinessItemNum = 0;
	    BigDecimal personDataTotalEstimatedSalesAmount = BigDecimal.ZERO;
	    int personDataTotalSuccessBusinessNum = 0;
	    int personDataTotalSuccessBusinessItemNum = 0;
	    BigDecimal personDataTotalSuccessEstimatedSalesAmount = BigDecimal.ZERO;

	    for (Map personData : personDataList) {

		personDataTotalBusinessNum = personDataTotalBusinessNum + (int) personData.get("businessNum");
		personDataTotalBusinessItemNum = personDataTotalBusinessItemNum
			+ (int) personData.get("businessItemNum");

		personDataTotalEstimatedSalesAmount = personDataTotalEstimatedSalesAmount
			.add((BigDecimal) personData.get("estimatedSalesAmount"));

		personDataTotalSuccessBusinessNum = personDataTotalSuccessBusinessNum
			+ (int) personData.get("successBusinessNum");
		personDataTotalSuccessBusinessItemNum = personDataTotalSuccessBusinessItemNum
			+ (int) personData.get("successBusinessItemNum");
		personDataTotalSuccessEstimatedSalesAmount = personDataTotalSuccessEstimatedSalesAmount
			.add((BigDecimal) personData.get("successEstimatedSalesAmount"));
	    }
	    Map personData2 = new HashMap();
	    personData2.put("rank", "汇总");
	    personData2.put("businessNum", personDataTotalBusinessNum);
	    personData2.put("businessItemNum", personDataTotalBusinessItemNum);
	    personData2.put("estimatedSalesAmount", personDataTotalEstimatedSalesAmount);
	    personData2.put("successBusinessNum", personDataTotalSuccessBusinessNum);
	    personData2.put("successBusinessItemNum", personDataTotalSuccessBusinessItemNum);
	    personData2.put("successEstimatedSalesAmount", personDataTotalSuccessEstimatedSalesAmount);
	    personDataList.add(personData2);

	    int buDataTotalBusinessNum = 0;
	    int buDataTotalBusinessItemNum = 0;
	    BigDecimal buDataTotalEstimatedSalesAmount = BigDecimal.ZERO;
	    int buDataTotalSuccessBusinessNum = 0;
	    int buDataTotalSuccessBusinessItemNum = 0;
	    BigDecimal buDataTotalSuccessEstimatedSalesAmount = BigDecimal.ZERO;
	    for (Map buData : buDataList) {
		buDataTotalBusinessNum = buDataTotalBusinessNum + (int) buData.get("businessNum");
		buDataTotalBusinessItemNum = buDataTotalBusinessItemNum + (int) buData.get("businessItemNum");
		buDataTotalEstimatedSalesAmount = buDataTotalEstimatedSalesAmount
			.add((BigDecimal) buData.get("estimatedSalesAmount"));
		buDataTotalSuccessBusinessNum = buDataTotalSuccessBusinessNum + (int) buData.get("successBusinessNum");
		buDataTotalSuccessBusinessNum = buDataTotalSuccessBusinessNum + (int) buData.get("successBusinessNum");
		buDataTotalSuccessEstimatedSalesAmount = buDataTotalSuccessEstimatedSalesAmount
			.add((BigDecimal) buData.get("successEstimatedSalesAmount"));

	    }
	    Map buData2 = new HashMap();
	    buData2.put("rank", "汇总");

	    buData2.put("businessNum", buDataTotalBusinessNum);
	    buData2.put("businessItemNum", buDataTotalBusinessItemNum);
	    buData2.put("estimatedSalesAmount", buDataTotalEstimatedSalesAmount);
	    buData2.put("successBusinessNum", buDataTotalSuccessBusinessNum);
	    buData2.put("successBusinessItemNum", buDataTotalSuccessBusinessItemNum);
	    buData2.put("successEstimatedSalesAmount", buDataTotalSuccessEstimatedSalesAmount);

	    buDataList.add(buData2);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	String fromDateDateFormat = simpleDateFormat.format(fromDate);
	String thruDateDateFormat = simpleDateFormat.format(thruDate);
	workMap.put("fromDate", fromDateDateFormat);
	workMap.put("thruDate", thruDateDateFormat);

	workMap.put("personDataList", personDataList);
	workMap.put("buDataList", buDataList);
	result.put("workMap", workMap);
	Debug.log("workMap ===" + workMap);
	return result;
    }

    /**
     * 商机排行榜 新的
     */
    public static Map<String, Object> crmBusinessRanking20(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();
	Map<String, Object> workMap = new HashMap<>();
	String dateTypeId = (String) context.get("dateTypeId");
	String typeId = (String) context.get("typeId");
	Timestamp createTime_fld0_value = (Timestamp) context.get("createTime_fld0_value");
	Timestamp createTime_fld1_value = (Timestamp) context.get("createTime_fld1_value");

	Map personDataCollection = new HashMap();
	Map buDataCollection = new HashMap();
	List<Map> personDataList = new ArrayList();

	List<Map> buDataList = new ArrayList();

	int fromDateNum = -31;
	if ("month".equals(dateTypeId)) {
	    fromDateNum = -31;
	}
	if ("quarter".equals(dateTypeId)) {
	    fromDateNum = -92;
	}
	if ("year".equals(dateTypeId)) {
	    fromDateNum = -365;
	}
	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(fromDateNum));

	if (UtilValidate.isNotEmpty(createTime_fld0_value)) {
	    fromDate = createTime_fld0_value;
	}
	if (UtilValidate.isNotEmpty(createTime_fld1_value)) {
	    thruDate = createTime_fld1_value;
	}
	try {
	    // 商机数量 商机金额 start
	    Map businessCollection = getBusinessCollection(delegator, fromDate, thruDate, typeId);
	    // 商机数量 商机金额 end

	    // 签约数量 签约金额
	    Map successBusinessCollection = getSuccessBusinessCollection(delegator, fromDate, thruDate, typeId);

	    // Debug.log("businessCollection ===" + businessCollection);
	    // Debug.log("successBusinessCollection ===" + successBusinessCollection);

	    Map mergeBusinessCollection = mergeBusinessCollection(businessCollection, successBusinessCollection);

	    // Debug.log("mergeBusinessCollection ===" + mergeBusinessCollection);

	    personDataCollection = (Map) mergeBusinessCollection.get("personDataCollection");
	    buDataCollection = (Map) mergeBusinessCollection.get("buDataCollection");
	    personDataList = new ArrayList<Map>(personDataCollection.values());
	    buDataList = new ArrayList<Map>(buDataCollection.values());

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	personDataList = addPersonPagingList(delegator, personDataList, fromDate, thruDate);
	// Debug.log("buDataList 4267===" + buDataList);
	buDataList = addBuPagingList(delegator, buDataList, fromDate, thruDate);
//    Debug.log("personDataList 69===" + personDataList);
	// Debug.log("buDataList 70===" + buDataList);
	// 按照签约金额进行倒序 排序
	Collections.sort(personDataList, new Comparator<Map>() {
	    @Override
	    public int compare(Map obj1, Map obj2) {
		// int i =
		// ((Integer)obj1.get("businessNum")).compareTo((Integer)obj2.get("businessNum"));//正序
		int i = ((BigDecimal) obj2.get("successEstimatedSalesAmount"))
			.compareTo((BigDecimal) obj1.get("successEstimatedSalesAmount"));
		return i;// 这里返回的只是一个int类型的数据
	    }
	});
	// Debug.log("personDataList sort===" + personDataList);
	// 按照签约金额倒序进行排序
	Collections.sort(buDataList, new Comparator<Map>() {
	    @Override
	    public int compare(Map obj1, Map obj2) {
		// int i =
		// ((Integer)obj1.get("businessNum")).compareTo((Integer)obj2.get("businessNum"));
		// //正序
		int i = ((BigDecimal) obj2.get("successEstimatedSalesAmount"))
			.compareTo((BigDecimal) obj1.get("successEstimatedSalesAmount"));
		return i;// 这里返回的只是一个int类型的数据
	    }
	});
	// Debug.log("buDataList sort===" + buDataList);

	Map personDataHuizong = getPersonDataHuizong(personDataList);
	personDataList.add(personDataHuizong);
//	    Debug.log("personDataHuizong===" + personDataHuizong);

	Map buDataHuizong = getBuDataHuizong(buDataList);
	buDataList.add(buDataHuizong);
//	    Debug.log("buDataHuizong===" + buDataHuizong);

	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	String fromDateDateFormat = simpleDateFormat.format(fromDate);
	String thruDateDateFormat = simpleDateFormat.format(thruDate);
	workMap.put("fromDate", fromDateDateFormat);
	workMap.put("thruDate", thruDateDateFormat);

	workMap.put("personDataList", personDataList);
	workMap.put("buDataList", buDataList);
	result.put("workMap", workMap);
	Debug.log("workMap ===" + workMap);
	return result;
    }

    private static List addPersonPagingList(Delegator delegator, List personDataList, Timestamp fromDate,
	    Timestamp thruDate) {
	List result = new ArrayList();

	ArrayList<EntityCondition> mainCond = new ArrayList<>();
	mainCond.add(
		EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("0", "1", "2", "3", "4")));

	mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
	mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO,
		UtilDateTime.getDayEnd(thruDate)));
	mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	ArrayList<EntityCondition> mainCond2 = new ArrayList<>();
	mainCond2.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("5")));

	mainCond2.add(EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
	mainCond2.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO,
		UtilDateTime.getDayEnd(thruDate)));
	mainCond2.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	try {
	    List<GenericValue> crmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);
	    List<GenericValue> crmBusinessList2 = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond2, EntityOperator.AND), null, null, null, true);
	    for (int i = 0; i < personDataList.size(); i++) {
		Map personData = (Map) personDataList.get(i);
//			    	Debug.log("personData 4345===" + personData);
		String personData_ownerUserId = (String) personData.get("ownerUserId");
		List list01234 = new ArrayList();
		for (GenericValue crmBusiness : crmBusinessList) {
		    Map business = new HashMap();
//		                Debug.log("crmBusiness 4350===" + crmBusiness);
		    String businessId = crmBusiness.getString("id");
		    String ownerUserId = crmBusiness.getString("ownerUserId");
		    if (personData_ownerUserId.equals(ownerUserId)) {

			business.put("businessId", businessId);
			business.put("personName", personData.get("personName"));
			business.put("buName", personData.get("buName"));
			business.put("ownerUserId", ownerUserId);
			business.put("businessName", crmBusiness.getString("businessName"));
			String customerId = crmBusiness.getString("customerId");
			business.put("customerId", customerId);
			business.put("customerId_dictText", customerIdDictText(delegator, customerId));
			String statusId = crmBusiness.getString("statusId");
			business.put("statusId", statusId);
			business.put("statusId_dictText", statusIdDictText(delegator, statusId));
			business.put("createTime", crmBusiness.getTimestamp("createTime"));

			list01234.add(business);
		    }

		}
		List list56 = new ArrayList();
		for (GenericValue crmBusiness : crmBusinessList2) {
		    Map business = new HashMap();
		    String businessId = crmBusiness.getString("id");
		    String ownerUserId = crmBusiness.getString("ownerUserId");
		    if (personData_ownerUserId.equals(ownerUserId)) {
			business.put("businessId", businessId);
			business.put("personName", personData.get("personName"));
			business.put("buName", personData.get("buName"));
			business.put("ownerUserId", ownerUserId);
			business.put("businessName", crmBusiness.getString("businessName"));
			String customerId = crmBusiness.getString("customerId");
			business.put("customerId", customerId);
			business.put("customerId_dictText", customerIdDictText(delegator, customerId));
			String statusId = crmBusiness.getString("statusId");
			business.put("statusId", statusId);
			business.put("statusId_dictText", statusIdDictText(delegator, statusId));
			business.put("createTime", crmBusiness.getTimestamp("createTime"));

			list56.add(business);
		    }

		}
		personData.put("list01234", list01234);
		personData.put("list56", list56);
		List list0123456 = new ArrayList();
		list0123456.addAll(list01234);
		list0123456.addAll(list56);
		personData.put("list0123456", list0123456);

		result.add(personData);
	    }

	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}

	return result;

    }

    private static String customerIdDictText(Delegator delegator, String customerId) throws GenericEntityException {
	String customerId_dictText = "";
	GenericValue crmCustomer = delegator.findOne("CrmCustomer", true, UtilMisc.toMap("id", customerId));
	if (UtilValidate.isNotEmpty(crmCustomer)) {
	    customerId_dictText = crmCustomer.getString("customerName");
	}
	return customerId_dictText;
    }

    private static String statusIdDictText(Delegator delegator, String statusId) throws GenericEntityException {
	String statusId_dictText = "";
	List<GenericValue> dataDictionaryInfo = delegator.findByAnd("DataDictionary",
		UtilMisc.toMap("dictionaryCode", statusId, "dictionaryTypeId", "BUSINESS_STATUS_ID"), null, true);
	GenericValue dataDictionary = EntityUtil.getFirst(dataDictionaryInfo);
	if (UtilValidate.isNotEmpty(dataDictionary)) {
	    statusId_dictText = dataDictionary.getString("description");
	}
	return statusId_dictText;
    }

    private static List addBuPagingList(Delegator delegator, List buDataList, Timestamp fromDate, Timestamp thruDate) {
	List result = new ArrayList();

	ArrayList<EntityCondition> mainCond = new ArrayList<>();
	mainCond.add(
		EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("0", "1", "2", "3", "4")));

	mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
	mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO,
		UtilDateTime.getDayEnd(thruDate)));
	mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	ArrayList<EntityCondition> mainCond2 = new ArrayList<>();
	mainCond2.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("5")));

	mainCond2.add(EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
	mainCond2.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO,
		UtilDateTime.getDayEnd(thruDate)));
	mainCond2.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	try {
	    List<GenericValue> crmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);
	    List<GenericValue> crmBusinessList2 = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond2, EntityOperator.AND), null, null, null, true);

	    for (int i = 0; i < buDataList.size(); i++) {
		Map buData = (Map) buDataList.get(i);
		String buData_buId = (String) buData.get("buId");
		String buData_buName = (String) buData.get("buName");

		List list01234 = new ArrayList();
		for (GenericValue crmBusiness : crmBusinessList) {
		    Map business = new HashMap();
		    String businessId = crmBusiness.getString("id");
		    String ownerUserId = crmBusiness.getString("ownerUserId");
		    String buId = getBuIdByUserLoginId(delegator, ownerUserId);
		    if (buData_buId.equals(buId)) {
			business.put("businessId", businessId);

			String personName = getPersonName(delegator, ownerUserId);
			business.put("personName", personName);
			business.put("buName", buData_buName);
			business.put("ownerUserId", ownerUserId);
			business.put("businessName", crmBusiness.getString("businessName"));
			String customerId = crmBusiness.getString("customerId");
			business.put("customerId", customerId);
			business.put("customerId_dictText", customerIdDictText(delegator, customerId));
			String statusId = crmBusiness.getString("statusId");
			business.put("statusId", statusId);
			business.put("statusId_dictText", statusIdDictText(delegator, statusId));
			business.put("createTime", crmBusiness.getTimestamp("createTime"));

			list01234.add(business);
		    }

		}
		List list56 = new ArrayList();
		for (GenericValue crmBusiness : crmBusinessList2) {
		    Map business = new HashMap();

		    String businessId = crmBusiness.getString("id");
		    String ownerUserId = crmBusiness.getString("ownerUserId");
		    String buId = getBuIdByUserLoginId(delegator, ownerUserId);
		    if (buData_buId.equals(buId)) {
			business.put("businessId", businessId);

			String personName = getPersonName(delegator, ownerUserId);
			business.put("personName", personName);
			business.put("buName", buData_buName);
			business.put("ownerUserId", ownerUserId);
			business.put("businessName", crmBusiness.getString("businessName"));
			String customerId = crmBusiness.getString("customerId");
			business.put("customerId", customerId);
			business.put("customerId_dictText", customerIdDictText(delegator, customerId));
			String statusId = crmBusiness.getString("statusId");
			business.put("statusId", statusId);
			business.put("statusId_dictText", statusIdDictText(delegator, statusId));
			business.put("createTime", crmBusiness.getTimestamp("createTime"));

			list56.add(business);
		    }

		}
		buData.put("list01234", list01234);
		buData.put("list56", list56);
		List list0123456 = new ArrayList();
		list0123456.addAll(list01234);
		list0123456.addAll(list56);
		buData.put("list0123456", list0123456);
		result.add(buData);

	    }
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}

	return result;

    }

    private static Map getBuDataHuizong(List<Map> buDataList) {
	int buDataTotalBusinessNum = 0;
	int buDataTotalBusinessItemNum = 0;
	BigDecimal buDataTotalEstimatedSalesAmount = BigDecimal.ZERO;
	int buDataTotalSuccessBusinessNum = 0;
	int buDataTotalSuccessBusinessItemNum = 0;
	BigDecimal buDataTotalSuccessEstimatedSalesAmount = BigDecimal.ZERO;
	for (Map buData : buDataList) {
	    buDataTotalBusinessNum = buDataTotalBusinessNum + (int) buData.get("businessNum");
	    buDataTotalBusinessItemNum = buDataTotalBusinessItemNum + (int) buData.get("businessItemNum");
	    buDataTotalEstimatedSalesAmount = buDataTotalEstimatedSalesAmount
		    .add((BigDecimal) buData.get("estimatedSalesAmount"));
	    buDataTotalSuccessBusinessNum = buDataTotalSuccessBusinessNum + (int) buData.get("successBusinessNum");
	    buDataTotalSuccessBusinessNum = buDataTotalSuccessBusinessNum + (int) buData.get("successBusinessNum");
	    buDataTotalSuccessEstimatedSalesAmount = buDataTotalSuccessEstimatedSalesAmount
		    .add((BigDecimal) buData.get("successEstimatedSalesAmount"));

	}
	Map buData2 = new HashMap();
	buData2.put("rank", "汇总");

	buData2.put("businessNum", buDataTotalBusinessNum);
	buData2.put("businessItemNum", buDataTotalBusinessItemNum);
	buData2.put("estimatedSalesAmount", buDataTotalEstimatedSalesAmount);
	buData2.put("successBusinessNum", buDataTotalSuccessBusinessNum);
	buData2.put("successBusinessItemNum", buDataTotalSuccessBusinessItemNum);
	buData2.put("successEstimatedSalesAmount", buDataTotalSuccessEstimatedSalesAmount);
	return buData2;
    }

    private static Map getPersonDataHuizong(List<Map> personDataList) {

	int personDataTotalBusinessNum = 0;
	int personDataTotalBusinessItemNum = 0;
	BigDecimal personDataTotalEstimatedSalesAmount = BigDecimal.ZERO;
	int personDataTotalSuccessBusinessNum = 0;
	int personDataTotalSuccessBusinessItemNum = 0;
	BigDecimal personDataTotalSuccessEstimatedSalesAmount = BigDecimal.ZERO;

	for (Map personData : personDataList) {

	    personDataTotalBusinessNum = personDataTotalBusinessNum + (int) personData.get("businessNum");
	    personDataTotalBusinessItemNum = personDataTotalBusinessItemNum + (int) personData.get("businessItemNum");

	    personDataTotalEstimatedSalesAmount = personDataTotalEstimatedSalesAmount
		    .add((BigDecimal) personData.get("estimatedSalesAmount"));

	    personDataTotalSuccessBusinessNum = personDataTotalSuccessBusinessNum
		    + (int) personData.get("successBusinessNum");
	    personDataTotalSuccessBusinessItemNum = personDataTotalSuccessBusinessItemNum
		    + (int) personData.get("successBusinessItemNum");
	    personDataTotalSuccessEstimatedSalesAmount = personDataTotalSuccessEstimatedSalesAmount
		    .add((BigDecimal) personData.get("successEstimatedSalesAmount"));
	}
	Map personData2 = new HashMap();
	personData2.put("rank", "汇总");
	personData2.put("businessNum", personDataTotalBusinessNum);
	personData2.put("businessItemNum", personDataTotalBusinessItemNum);
	personData2.put("estimatedSalesAmount", personDataTotalEstimatedSalesAmount);
	personData2.put("successBusinessNum", personDataTotalSuccessBusinessNum);
	personData2.put("successBusinessItemNum", personDataTotalSuccessBusinessItemNum);
	personData2.put("successEstimatedSalesAmount", personDataTotalSuccessEstimatedSalesAmount);

	return personData2;
	//
    }

    private static Map getBusinessCollection(Delegator delegator, Timestamp fromDate, Timestamp thruDate, String typeId)
	    throws GenericEntityException {
	Map personDataCollection = new HashMap();
	Map buDataCollection = new HashMap();
	ArrayList<EntityCondition> mainCond = new ArrayList<>();
	mainCond.add(
		EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("0", "1", "2", "3", "4")));

	mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
	mainCond.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO,
		UtilDateTime.getDayEnd(thruDate)));
	mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	List<GenericValue> crmBusinessList = delegator.findList("CrmBusiness",
		EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);
	// 商机数量 商机金额 start
	for (GenericValue crmBusiness : crmBusinessList) {

	    String businessId = crmBusiness.getString("id");
	    String ownerUserId = crmBusiness.getString("ownerUserId");
	    if ("public".equals(ownerUserId)) {
		continue;
	    }

	    String statusId = crmBusiness.getString("statusId");

	    Map param = UtilMisc.toMap("businessId", businessId);
	    if (UtilValidate.isNotEmpty(typeId)) {
		param.put("typeId", typeId);
	    }
	    List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null, true);

	    BigDecimal totalEstimatedSalesAmount = BigDecimal.ZERO;
	    int businessItemNum = 0;
	    for (GenericValue crmBusinessItem : crmBusinessItemList) {
		if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
		    BigDecimal estimatedSalesAmount = crmBusinessItem.getBigDecimal("estimatedSalesAmount");
		    totalEstimatedSalesAmount = totalEstimatedSalesAmount.add(estimatedSalesAmount);
		}
	    }
	    Map personData = new HashMap();
	    personData.put("ownerUserId", ownerUserId);
	    personData.put("statusId", statusId);
	    personData.put("estimatedSalesAmount", totalEstimatedSalesAmount);
	    personData.put("businessItemNum", crmBusinessItemList.size());
	    if (crmBusinessItemList.size() > 0) {
		personDataCollection = addPersonDataCollectionBusinessNum20(delegator, personDataCollection,
			personData);
		buDataCollection = addBuDataCollectionBusinessNum20(delegator, buDataCollection, personData);
	    }

	}

	Map result = new HashMap();
	result.put("personDataCollection", personDataCollection);
	result.put("buDataCollection", buDataCollection);
	return result;
    }

    private static Map getSuccessBusinessCollection(Delegator delegator, Timestamp fromDate, Timestamp thruDate,
	    String typeId) throws GenericEntityException {
	Map personDataCollection = new HashMap();
	Map buDataCollection = new HashMap();
	ArrayList<EntityCondition> mainCond = new ArrayList<>();
	// mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS,
	// "5"));

	mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("5")));

	mainCond.add(EntityCondition.makeCondition("status5Time", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
	mainCond.add(EntityCondition.makeCondition("status5Time", EntityOperator.LESS_THAN_EQUAL_TO,
		UtilDateTime.getDayEnd(thruDate)));
	mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	List<GenericValue> crmBusinessList = delegator.findList("CrmBusiness",
		EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);

//	    Debug.log("SuccessBusinesscrmBusinessList = "+crmBusinessList);
	Debug.log("SuccessBusinesscrmBusinessList = ");
	// 商机数量 商机金额 start
	for (GenericValue crmBusiness : crmBusinessList) {

	    String businessId = crmBusiness.getString("id");
	    String ownerUserId = crmBusiness.getString("ownerUserId");
	    if ("public".equals(ownerUserId)) {
		continue;
	    }

	    String statusId = crmBusiness.getString("statusId");

	    Map param = UtilMisc.toMap("businessId", businessId);
	    if (UtilValidate.isNotEmpty(typeId)) {
		param.put("typeId", typeId);
	    }
	    List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem", param, null, true);

	    BigDecimal totalEstimatedSalesAmount = BigDecimal.ZERO;
	    int businessItemNum = 0;
	    for (GenericValue crmBusinessItem : crmBusinessItemList) {
		if (UtilValidate.isNotEmpty(crmBusinessItem.getBigDecimal("estimatedSalesAmount"))) {
		    BigDecimal estimatedSalesAmount = crmBusinessItem.getBigDecimal("estimatedSalesAmount");
		    totalEstimatedSalesAmount = totalEstimatedSalesAmount.add(estimatedSalesAmount);
		}
	    }
	    Map personData = new HashMap();
	    personData.put("ownerUserId", ownerUserId);
	    personData.put("statusId", statusId);
	    personData.put("estimatedSalesAmount", totalEstimatedSalesAmount);
	    personData.put("businessItemNum", crmBusinessItemList.size());

	    if (crmBusinessItemList.size() > 0) {

		// TODO
		personDataCollection = addPersonDataCollectionSuccessBusinessNum20(delegator, personDataCollection,
			personData);
		buDataCollection = addBuDataCollectionSuccessBusinessNum20(delegator, buDataCollection, personData);
	    }

	}

	Map result = new HashMap();
	result.put("personDataCollection", personDataCollection);
	result.put("buDataCollection", buDataCollection);
	return result;
    }

    private static Map mergeBusinessCollection(Map businessCollection, Map successBusinessCollection) {

	Map<String, Map> personDataCollection = (Map) businessCollection.get("personDataCollection");
	Map<String, Map> buDataCollection = (Map) businessCollection.get("buDataCollection");
	Map<String, Map> personDataCollectionSuccess = (Map) successBusinessCollection.get("personDataCollection");
	Map<String, Map> buDataCollectionSuccess = (Map) successBusinessCollection.get("buDataCollection");
	Map personDataCollectionMerge = personDataCollection;
	Map buDataCollectionMerge = buDataCollection;

	for (String key : personDataCollectionSuccess.keySet()) {
	    Map personSuccess = personDataCollectionSuccess.get(key);
	    if (UtilValidate.isNotEmpty(personDataCollection.get(key))) {
		Map person = personDataCollection.get(key);
		person.put("successBusinessNum", personSuccess.get("successBusinessNum"));
		person.put("successBusinessItemNum", personSuccess.get("successBusinessItemNum"));
		person.put("successEstimatedSalesAmount", personSuccess.get("successEstimatedSalesAmount"));
		personDataCollectionMerge.put(key, person);
	    } else {
		personSuccess.put("businessNum", 0);
		personSuccess.put("estimatedSalesAmount", BigDecimal.ZERO);
		personSuccess.put("businessNum", 0);
		personSuccess.put("businessItemNum", 0);
		personDataCollectionMerge.put(key, personSuccess);
	    }
	}

	for (String buId : buDataCollectionSuccess.keySet()) {
	    Map buSuccess = buDataCollectionSuccess.get(buId);
	    if (UtilValidate.isNotEmpty(buDataCollection.get(buId))) {
		Map bu = buDataCollection.get(buId);
		bu.put("successBusinessNum", buSuccess.get("successBusinessNum"));
		bu.put("successBusinessItemNum", buSuccess.get("successBusinessItemNum"));
		bu.put("successEstimatedSalesAmount", buSuccess.get("successEstimatedSalesAmount"));
		buDataCollectionMerge.put(buId, bu);
	    } else {
		buSuccess.put("businessNum", 0);
		buSuccess.put("estimatedSalesAmount", BigDecimal.ZERO);
		buSuccess.put("businessNum", 0);
		buSuccess.put("businessItemNum", 0);
		buDataCollectionMerge.put(buId, buSuccess);
	    }
	}

	Map result = new HashMap();
	result.put("personDataCollection", personDataCollectionMerge);
	result.put("buDataCollection", buDataCollectionMerge);
	return result;
    }

    private static Map addPersonDataCollectionBusinessNum1(Delegator delegator, Map personDataCollection,
	    Map newPersonData) throws GenericEntityException {
	Map result = personDataCollection;
	// Debug.log("personDataCollection = " + personDataCollection);
	String newOwnerUserId = (String) newPersonData.get("ownerUserId");
	String newStatusId = (String) newPersonData.get("statusId");
	BigDecimal newEstimatedSalesAmount = (BigDecimal) newPersonData.get("estimatedSalesAmount");

	Map personData = new HashMap();

	if (UtilValidate.isEmpty(personDataCollection.get(newOwnerUserId))) {

	    String personName = getPersonName(delegator, newOwnerUserId);
	    String buName = getBuNameByUserLoginId(delegator, newOwnerUserId);
	    personData.put("personName", personName);
	    personData.put("buName", buName);
	    personData.put("ownerUserId", newOwnerUserId);
	    personData.put("estimatedSalesAmount", newEstimatedSalesAmount);
	} else {
	    Map oldPersonData = (Map) personDataCollection.get(newOwnerUserId);
	    personData.putAll(oldPersonData);

	    BigDecimal estimatedSalesAmount = newEstimatedSalesAmount
		    .add((BigDecimal) oldPersonData.get("estimatedSalesAmount"));
	    personData.put("estimatedSalesAmount", estimatedSalesAmount);
	}
	result.put(newOwnerUserId, personData);

	return result;

    }

    // 处理商机排行榜 个人累加数据
    private static Map addPersonDataCollectionBusinessNum(Delegator delegator, Map personDataCollection,
	    Map newPersonData) throws GenericEntityException {
	Map result = personDataCollection;
	// Debug.log("personDataCollection = " + personDataCollection);
	String newOwnerUserId = (String) newPersonData.get("ownerUserId");
	String newStatusId = (String) newPersonData.get("statusId");
	BigDecimal newEstimatedSalesAmount = (BigDecimal) newPersonData.get("estimatedSalesAmount");
	Integer newBusinessItemNum = (Integer) newPersonData.get("businessItemNum");

	Map personData = new HashMap();

	if (UtilValidate.isEmpty(personDataCollection.get(newOwnerUserId))) {

	    String personName = getPersonName(delegator, newOwnerUserId);
	    String buName = getBuNameByUserLoginId(delegator, newOwnerUserId);
	    personData.put("personName", personName);
	    personData.put("buName", buName);
	    personData.put("ownerUserId", newOwnerUserId);
	    personData.put("businessNum", 1);
	    personData.put("businessItemNum", newBusinessItemNum);
	    personData.put("estimatedSalesAmount", newEstimatedSalesAmount);
	    // if("5".equals(newStatusId)) {
	    if ("5".equals(newStatusId)) {
		personData.put("successBusinessNum", 1);
		personData.put("successBusinessItemNum", newBusinessItemNum);
		personData.put("successEstimatedSalesAmount", newEstimatedSalesAmount);
	    } else {
		personData.put("successBusinessNum", 0);
		personData.put("successBusinessItemNum", 0);
		personData.put("successEstimatedSalesAmount", BigDecimal.ZERO);
	    }

	} else {
	    Map oldPersonData = (Map) personDataCollection.get(newOwnerUserId);
	    // Debug.log("oldPersonData = " + oldPersonData);
	    personData.putAll(oldPersonData);
	    // Debug.log("oldPersonData.get(businessNum) = " +
	    // oldPersonData.get("businessNum"));
	    int businessNum = (int) oldPersonData.get("businessNum") + 1;

	    // Debug.log("businessNum = " + businessNum);
	    personData.put("businessNum", businessNum);

	    Integer businessItemNum = newBusinessItemNum + (Integer) oldPersonData.get("businessItemNum");
	    personData.put("businessItemNum", businessItemNum);
	    BigDecimal estimatedSalesAmount = newEstimatedSalesAmount
		    .add((BigDecimal) oldPersonData.get("estimatedSalesAmount"));
	    personData.put("estimatedSalesAmount", estimatedSalesAmount);
//    		if("5".equals(newStatusId)) {
	    if ("5".equals(newStatusId)) {
		int successBusinessNum = (int) oldPersonData.get("successBusinessNum") + 1;
		personData.put("successBusinessNum", successBusinessNum);
		Integer successBusinessItemNum = newBusinessItemNum + (Integer) oldPersonData.get("businessItemNum");
		personData.put("successBusinessItemNum", successBusinessItemNum);
		BigDecimal successEstimatedSalesAmount = newEstimatedSalesAmount
			.add((BigDecimal) oldPersonData.get("successEstimatedSalesAmount"));
		personData.put("successEstimatedSalesAmount", successEstimatedSalesAmount);
	    }

	}

	result.put(newOwnerUserId, personData);

	return result;

    }

    // 处理商机排行榜 个人累加数据
    private static Map addPersonDataCollectionBusinessNum20(Delegator delegator, Map personDataCollection,
	    Map newPersonData) throws GenericEntityException {
	Map result = personDataCollection;
	// Debug.log("personDataCollection = " + personDataCollection);
	String newOwnerUserId = (String) newPersonData.get("ownerUserId");
	String newStatusId = (String) newPersonData.get("statusId");
	BigDecimal newEstimatedSalesAmount = BigDecimal.ZERO;
	if (UtilValidate.isNotEmpty(newPersonData.get("estimatedSalesAmount"))) {
	    newEstimatedSalesAmount = (BigDecimal) newPersonData.get("estimatedSalesAmount");
	}
	Integer newBusinessItemNum = 0;
	if (UtilValidate.isNotEmpty(newPersonData.get("businessItemNum"))) {
	    newBusinessItemNum = (Integer) newPersonData.get("businessItemNum");
	}

	Map personData = new HashMap();

	if (UtilValidate.isEmpty(personDataCollection.get(newOwnerUserId))) {

	    String personName = getPersonName(delegator, newOwnerUserId);
	    String buName = getBuNameByUserLoginId(delegator, newOwnerUserId);
	    personData.put("personName", personName);
	    personData.put("buName", buName);
	    personData.put("ownerUserId", newOwnerUserId);
	    personData.put("businessNum", 1);
	    personData.put("businessItemNum", newBusinessItemNum);
	    personData.put("estimatedSalesAmount", newEstimatedSalesAmount);

	    personData.put("successBusinessNum", 0);
	    personData.put("successBusinessItemNum", 0);
	    personData.put("successEstimatedSalesAmount", BigDecimal.ZERO);
	} else {
	    Map oldPersonData = (Map) personDataCollection.get(newOwnerUserId);
	    personData.putAll(oldPersonData);
	    int businessNum = (int) oldPersonData.get("businessNum") + 1;
	    personData.put("businessNum", businessNum);

	    Integer businessItemNum = newBusinessItemNum + (Integer) oldPersonData.get("businessItemNum");
	    personData.put("businessItemNum", businessItemNum);
	    BigDecimal estimatedSalesAmount = newEstimatedSalesAmount
		    .add((BigDecimal) oldPersonData.get("estimatedSalesAmount"));
	    personData.put("estimatedSalesAmount", estimatedSalesAmount);

	}

	result.put(newOwnerUserId, personData);

	return result;

    }

    // 处理商机排行榜 个人累加数据
    private static Map addPersonDataCollectionSuccessBusinessNum20(Delegator delegator, Map personDataCollection,
	    Map newPersonData) {
	Map result = personDataCollection;
	Debug.log("personDataCollection = " + personDataCollection);
	Debug.log("newPersonData = " + newPersonData);
	String newOwnerUserId = (String) newPersonData.get("ownerUserId");
	String newStatusId = (String) newPersonData.get("statusId");

	BigDecimal newEstimatedSalesAmount = BigDecimal.ZERO;
	int newBusinessItemNum = 0;
	if (UtilValidate.isNotEmpty(newPersonData.get("estimatedSalesAmount"))) {
	    newEstimatedSalesAmount = (BigDecimal) newPersonData.get("estimatedSalesAmount");
	}
	if (UtilValidate.isNotEmpty(newPersonData.get("businessItemNum"))) {
	    newBusinessItemNum = (Integer) newPersonData.get("businessItemNum");
	}
//	if("13681387430".equals(newOwnerUserId)) {
	try {
	    Map personData = new HashMap();

//	ownerUserId,13681387430
	    Debug.log(newOwnerUserId + "4610 = " + personData);

	    if (UtilValidate.isEmpty(personDataCollection.get(newOwnerUserId))) {

		String personName = getPersonName(delegator, newOwnerUserId);
		String buName = getBuNameByUserLoginId(delegator, newOwnerUserId);
		personData.put("personName", personName);
		personData.put("buName", buName);
		personData.put("ownerUserId", newOwnerUserId);

		personData.put("successBusinessNum", 1);
		personData.put("successBusinessItemNum", newBusinessItemNum);
		personData.put("successEstimatedSalesAmount", newEstimatedSalesAmount);

	    } else {
		Map oldPersonData = (Map) personDataCollection.get(newOwnerUserId);
		personData.putAll(oldPersonData);
		Debug.log(newOwnerUserId + "4627 = " + oldPersonData.get("successBusinessNum"));
		int successBusinessNum = (int) oldPersonData.get("successBusinessNum") + 1;
		Debug.log(newOwnerUserId + "4629 = " + successBusinessNum);
		personData.put("successBusinessNum", successBusinessNum);
		Debug.log(newOwnerUserId + "4630 = " + personData);
		Debug.log(newOwnerUserId + "4631 = " + oldPersonData.get("successBusinessItemNum"));
		int successBusinessItemNum = newBusinessItemNum + (int) oldPersonData.get("successBusinessItemNum");
		personData.put("successBusinessItemNum", successBusinessItemNum);
		Debug.log(newOwnerUserId + "4633 = " + personData);
		BigDecimal successEstimatedSalesAmount = newEstimatedSalesAmount
			.add((BigDecimal) oldPersonData.get("successEstimatedSalesAmount"));
		personData.put("successEstimatedSalesAmount", successEstimatedSalesAmount);

	    }
	    // Debug.log(newOwnerUserId + "4640 = " + personData);
	    result.put(newOwnerUserId, personData);
	} catch (Exception e) {
	    Debug.log("addPersonDataCollectionSuccessBusinessNum20 = " + e.getMessage());
	}
//	}
	return result;

    }

    private static Map addBuDataCollectionBusinessNum1(Delegator delegator, Map buDataCollection, Map newBuData)
	    throws GenericEntityException {
	Map result = buDataCollection;
	String newOwnerUserId = (String) newBuData.get("ownerUserId");
	String newStatusId = (String) newBuData.get("statusId");
	BigDecimal newEstimatedSalesAmount = (BigDecimal) newBuData.get("estimatedSalesAmount");
	if (UtilValidate.isEmpty(newEstimatedSalesAmount)) {
	    newEstimatedSalesAmount = BigDecimal.ZERO;
	}

	String buId = getBuIdByUserLoginId(delegator, newOwnerUserId);

	Map buData = new HashMap();
	if (UtilValidate.isEmpty(buDataCollection.get(buId))) {

	    String buName = getBuName(delegator, buId);
	    buData.put("buId", buId);
	    buData.put("buName", buName);
	    buData.put("estimatedSalesAmount", newEstimatedSalesAmount);
	} else {

	    Map oldBuData = (Map) buDataCollection.get(buId);
	    buData.putAll(oldBuData);
	    BigDecimal estimatedSalesAmount = newEstimatedSalesAmount
		    .add((BigDecimal) oldBuData.get("estimatedSalesAmount"));
	    buData.put("estimatedSalesAmount", estimatedSalesAmount);
	}
	result.put(buId, buData);
	return result;

    }

    private static Map addInvDataCollectionBusinessNum1(Delegator delegator, Map dataCollection, Map newData)
	    throws GenericEntityException {
	Map result = dataCollection;
	String inventoryId = (String) newData.get("inventoryId");
	String warehouseName = (String) newData.get("warehouseName");
	BigDecimal newEstimatedSalesAmount = (BigDecimal) newData.get("estimatedSalesAmount");
	if (UtilValidate.isEmpty(newEstimatedSalesAmount)) {
	    newEstimatedSalesAmount = BigDecimal.ZERO;
	}
	if (UtilValidate.isEmpty(inventoryId)) {
	    return result;
	}
//    	if (UtilValidate.isEmpty(warehouseName)) {
//    		warehouseName = "未选择仓库";
//    	}

	Map data = new HashMap();
	if (UtilValidate.isEmpty(dataCollection.get(inventoryId))) {

	    data.put("inventoryId", inventoryId);
	    data.put("warehouseName", warehouseName);
	    data.put("estimatedSalesAmount", newEstimatedSalesAmount);
	} else {

	    Map oldData = (Map) dataCollection.get(inventoryId);
	    data.putAll(oldData);
	    BigDecimal estimatedSalesAmount = newEstimatedSalesAmount
		    .add((BigDecimal) oldData.get("estimatedSalesAmount"));
	    data.put("estimatedSalesAmount", estimatedSalesAmount);
	}
	result.put(inventoryId, data);
	return result;

    }

    // 处理商机排行榜 部门累加数据
    private static Map addBuDataCollectionBusinessNum(Delegator delegator, Map buDataCollection, Map newBuData)
	    throws GenericEntityException {
	Map result = buDataCollection;
	String newOwnerUserId = (String) newBuData.get("ownerUserId");
	String newStatusId = (String) newBuData.get("statusId");
	BigDecimal newEstimatedSalesAmount = (BigDecimal) newBuData.get("estimatedSalesAmount");
	if (UtilValidate.isEmpty(newEstimatedSalesAmount)) {
	    newEstimatedSalesAmount = BigDecimal.ZERO;
	}

	Integer newBusinessItemNum = (Integer) newBuData.get("businessItemNum");

	String buId = getBuIdByUserLoginId(delegator, newOwnerUserId);

	Map buData = new HashMap();
	if (UtilValidate.isEmpty(buDataCollection.get(buId))) {

	    String buName = getBuName(delegator, buId);
	    buData.put("buId", buId);
	    buData.put("buName", buName);
	    buData.put("businessNum", 1);
	    buData.put("businessItemNum", newBusinessItemNum);
	    buData.put("estimatedSalesAmount", newEstimatedSalesAmount);

	    if ("5".equals(newStatusId)) {
// 		   if("5".equals(newStatusId)) {
		buData.put("successBusinessNum", 1);
		buData.put("successBusinessItemNum", newBusinessItemNum);
		buData.put("successEstimatedSalesAmount", newEstimatedSalesAmount);
	    } else {
		buData.put("successBusinessNum", 0);
		buData.put("successBusinessItemNum", 0);
		buData.put("successEstimatedSalesAmount", BigDecimal.ZERO);
	    }

	} else {

	    Map oldBuData = (Map) buDataCollection.get(buId);
	    buData.putAll(oldBuData);
	    int businessNum = (int) oldBuData.get("businessNum") + 1;
	    buData.put("businessNum", businessNum);
	    Integer businessItemNum = newBusinessItemNum + (Integer) oldBuData.get("businessItemNum");
	    buData.put("businessItemNum", businessItemNum);
	    BigDecimal estimatedSalesAmount = newEstimatedSalesAmount
		    .add((BigDecimal) oldBuData.get("estimatedSalesAmount"));
	    buData.put("estimatedSalesAmount", estimatedSalesAmount);
//    		if("5".equals(newStatusId)) {
	    if ("5".equals(newStatusId)) {
		int successBusinessNum = (int) oldBuData.get("successBusinessNum") + 1;
		buData.put("successBusinessNum", successBusinessNum);
		Integer successBusinessItemNum = newBusinessItemNum + (Integer) oldBuData.get("businessItemNum");
		buData.put("successBusinessItemNum", successBusinessItemNum);
		BigDecimal successEstimatedSalesAmount = newEstimatedSalesAmount
			.add((BigDecimal) oldBuData.get("successEstimatedSalesAmount"));
		buData.put("successEstimatedSalesAmount", successEstimatedSalesAmount);
	    }

	}

	result.put(buId, buData);

	return result;

    }

    // 处理商机排行榜 部门累加数据
    private static Map addBuDataCollectionBusinessNum20(Delegator delegator, Map buDataCollection, Map newBuData)
	    throws GenericEntityException {
	Map result = buDataCollection;
	String newOwnerUserId = (String) newBuData.get("ownerUserId");
	String newStatusId = (String) newBuData.get("statusId");
	BigDecimal newEstimatedSalesAmount = BigDecimal.ZERO;
	if (UtilValidate.isNotEmpty(newBuData.get("estimatedSalesAmount"))) {
	    newEstimatedSalesAmount = (BigDecimal) newBuData.get("estimatedSalesAmount");
	}

	Integer newBusinessItemNum = 0;
	if (UtilValidate.isNotEmpty(newBuData.get("businessItemNum"))) {
	    newBusinessItemNum = (Integer) newBuData.get("businessItemNum");
	}
	String buId = getBuIdByUserLoginId(delegator, newOwnerUserId);

	Map buData = new HashMap();
	if (UtilValidate.isEmpty(buDataCollection.get(buId))) {

	    String buName = getBuName(delegator, buId);
	    buData.put("buId", buId);
	    buData.put("buName", buName);
	    buData.put("businessNum", 1);
	    buData.put("businessItemNum", newBusinessItemNum);
	    buData.put("estimatedSalesAmount", newEstimatedSalesAmount);

	    buData.put("successBusinessNum", 0);
	    buData.put("successBusinessItemNum", 0);
	    buData.put("successEstimatedSalesAmount", BigDecimal.ZERO);

	} else {

	    Map oldBuData = (Map) buDataCollection.get(buId);
	    buData.putAll(oldBuData);
	    int businessNum = (int) oldBuData.get("businessNum") + 1;
	    buData.put("businessNum", businessNum);
	    Integer businessItemNum = newBusinessItemNum + (Integer) oldBuData.get("businessItemNum");
	    buData.put("businessItemNum", businessItemNum);
	    BigDecimal estimatedSalesAmount = newEstimatedSalesAmount
		    .add((BigDecimal) oldBuData.get("estimatedSalesAmount"));
	    buData.put("estimatedSalesAmount", estimatedSalesAmount);

	}

	result.put(buId, buData);

	return result;

    }

    // 处理商机排行榜 部门累加数据
    private static Map addBuDataCollectionSuccessBusinessNum20(Delegator delegator, Map buDataCollection,
	    Map newBuData) {
	// Debug.log(" addBuDataCollectionSuccessBusinessNum20 newBuData ="+newBuData);
	Map result = buDataCollection;
	String newOwnerUserId = (String) newBuData.get("ownerUserId");
	// Debug.log("newOwnerUserId ="+newOwnerUserId);
	String newStatusId = (String) newBuData.get("statusId");
	// Debug.log("newStatusId ="+newStatusId);
	BigDecimal newEstimatedSalesAmount = BigDecimal.ZERO;
	if (UtilValidate.isNotEmpty(newBuData.get("estimatedSalesAmount"))) {
	    newEstimatedSalesAmount = (BigDecimal) newBuData.get("estimatedSalesAmount");
	}

	Integer newBusinessItemNum = 0;
	if (UtilValidate.isNotEmpty(newBuData.get("businessItemNum"))) {
	    newBusinessItemNum = (Integer) newBuData.get("businessItemNum");
	}
	try {
	    String buId = getBuIdByUserLoginId(delegator, newOwnerUserId);
	    // Debug.log("buId ="+buId);
	    Map buData = new HashMap();
	    if (UtilValidate.isEmpty(buDataCollection.get(buId))) {

		String buName = getBuName(delegator, buId);
		buData.put("buId", buId);
		buData.put("buName", buName);

		buData.put("successBusinessNum", 1);
		buData.put("successBusinessItemNum", newBusinessItemNum);
		buData.put("successEstimatedSalesAmount", newEstimatedSalesAmount);

		// Debug.log("empty buData ="+buData);
	    } else {

		Map oldBuData = (Map) buDataCollection.get(buId);
		buData.putAll(oldBuData);

		int successBusinessNum = (int) oldBuData.get("successBusinessNum") + 1;
		buData.put("successBusinessNum", successBusinessNum);
		Integer successBusinessItemNum = newBusinessItemNum + (Integer) oldBuData.get("successBusinessItemNum");
		buData.put("successBusinessItemNum", successBusinessItemNum);
		BigDecimal successEstimatedSalesAmount = newEstimatedSalesAmount
			.add((BigDecimal) oldBuData.get("successEstimatedSalesAmount"));
		buData.put("successEstimatedSalesAmount", successEstimatedSalesAmount);
		// Debug.log("notempty buData ="+buData);

	    }

	    result.put(buId, buData);
	} catch (Exception e) {
	    Debug.log("addBuDataCollectionSuccessBusinessNum20 =" + e.getMessage());
	}
	return result;

    }

    private static boolean greaterThan(BigDecimal num1, BigDecimal num2) {
	boolean result = false;
	if (num1.compareTo(num2) == 1) {
	    result = true;
	}
	return result;

    }

    private static boolean lessThan(BigDecimal num1, BigDecimal num2) {
	boolean result = false;
	if (num1.compareTo(num2) == -1) {
	    result = true;
	}
	return result;

    }

    private static Map addPersonDataCollectionCustomer(Delegator delegator, Map personDataCollection, Map newPersonData)
	    throws GenericEntityException {
	Map result = personDataCollection;
	String newOwnerUserId = (String) newPersonData.get("ownerUserId");

	if (UtilValidate.isEmpty(personDataCollection.get(newOwnerUserId))) {
	    Map personData = new HashMap();
	    String personName = getPersonName(delegator, newOwnerUserId);
	    String buName = getBuNameByUserLoginId(delegator, newOwnerUserId);
	    personData.put("personName", personName);
	    personData.put("buName", buName);
	    personData.put("ownerUserId", newOwnerUserId);
	    int customerNum = 1;
	    personData.put("customerNum", customerNum);

	    result.put(newOwnerUserId, personData);
	} else {
	    Map personData = new HashMap();
	    Map oldPersonData = (Map) personDataCollection.get(newOwnerUserId);
	    personData.putAll(oldPersonData);
	    int customerNum = (int) oldPersonData.get("customerNum") + 1;
	    personData.put("customerNum", customerNum);
	    result.put(newOwnerUserId, personData);
	}
	return result;

    }

    private static Map addBuDataCollectionCustomer(Delegator delegator, Map buDataCollection, Map newBuData)
	    throws GenericEntityException {
	Map result = buDataCollection;
	String newOwnerUserId = (String) newBuData.get("ownerUserId");

	String buId = getBuIdByUserLoginId(delegator, newOwnerUserId);

	if (UtilValidate.isEmpty(buDataCollection.get(buId))) {
	    Map buData = new HashMap();
	    String buName = getBuName(delegator, buId);
	    buData.put("buId", buId);
	    buData.put("buName", buName);
	    int customerNum = 1;
	    buData.put("customerNum", customerNum);
	    result.put(buId, buData);
	} else {
	    Map buData = new HashMap();
	    Map oldBuData = (Map) buDataCollection.get(buId);
	    buData.putAll(oldBuData);
	    int customerNum = (int) oldBuData.get("customerNum") + 1;
	    buData.put("customerNum", customerNum);
	    result.put(buId, buData);
	}
	return result;

    }

    // crm 同名方法
    private static String getPersonName(Delegator delegator, String userLoginId) throws GenericEntityException {
	String result = "";

	GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId), true);

	if (UtilValidate.isNotEmpty(userLogin)) {
	    GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", userLogin.getString("partyId")),
		    true);
	    if (UtilValidate.isNotEmpty(person)) {
		String personName = person.getString("name");
		result = personName;
	    }
	}
	return result;
    }

    private static String getBuIdByUserLoginId(Delegator delegator, String userLoginId) throws GenericEntityException {
	String result = "";

	List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship", UtilMisc.toMap("partyIdTo",
		userLoginId, "statusId", "PARTY_ENABLED", "partyRelationshipTypeId", "COMPANY_EMPLOYEE"), null, true);
	GenericValue coRelationship = EntityUtil.getFirst(coRelationshipList);
	if (UtilValidate.isNotEmpty(coRelationship)) {
	    result = coRelationship.getString("partyIdFrom");
	}

	return result;
    }

    private static String getBuName(Delegator delegator, String buId) throws GenericEntityException {
	String result = "";
	List<GenericValue> dataDictionaryList = delegator.findByAnd("DataDictionary",
		UtilMisc.toMap("dictionaryCode", buId, "dictionaryTypeId", "BU_DEPARTMENT"), null, true);

	GenericValue dataDictionary = EntityUtil.getFirst(dataDictionaryList);
	if (UtilValidate.isNotEmpty(dataDictionary)) {
	    String description = dataDictionary.getString("description");
	    result = description;
	}
	return result;
    }

    private static String getBuNameByUserLoginId(Delegator delegator, String userLoginId)
	    throws GenericEntityException {
	String result = "";

	List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship", UtilMisc.toMap("partyIdTo",
		userLoginId, "statusId", "PARTY_ENABLED", "partyRelationshipTypeId", "COMPANY_EMPLOYEE"), null, true);
	GenericValue coRelationship = EntityUtil.getFirst(coRelationshipList);
	if (UtilValidate.isNotEmpty(coRelationship)) {
	    String buId = coRelationship.getString("partyIdFrom");
	    List<GenericValue> dataDictionaryList = delegator.findByAnd("DataDictionary",
		    UtilMisc.toMap("dictionaryCode", buId, "dictionaryTypeId", "BU_DEPARTMENT"), null, true);

	    GenericValue dataDictionary = EntityUtil.getFirst(dataDictionaryList);
	    if (UtilValidate.isNotEmpty(dataDictionary)) {
		String description = dataDictionary.getString("description");
		result = description;
	    }
	}

	return result;
    }

    public static Map<String, Object> collideCustomerName(DispatchContext dctx, Map<String, ? extends Object> context) {

	Map result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();

	try {
	    List list2 = new ArrayList();

	    List mainCond = new ArrayList();

	    mainCond.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.NOT_EQUAL, "public"));
	    mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    List<GenericValue> customerList = delegator.findList("CrmCustomer",
		    EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, UtilMisc.toList("-createdStamp"),
		    null, true);
	    List<GenericValue> collideTypeList = delegator.findByAnd("DataDictionary",
		    UtilMisc.toMap("dictionaryTypeId", "COLLIDE_TYPE"), null, true);
	    for (int i = 0; i < customerList.size(); i++) {
		GenericValue customer = customerList.get(i);
		String ss = customer.getString("customerName");
		for (int j = 0; j < collideTypeList.size(); j++) {
		    GenericValue collideGv = collideTypeList.get(j);
		    String collideType = collideGv.getString("description");
		    ss = ss.replace(collideType, "");
		}
		list2.add(ss);
	    }

	    Map dataCollection = new HashMap();

	    for (int j = 0; j < list2.size(); j++) {
		String s2 = (String) list2.get(j);
		Map newData = new HashMap();
		newData.put("id", s2);
		dataCollection = addDataCollection(dataCollection, newData);
	    }

	    dataCollection = computerData(delegator, dataCollection, customerList);

	    Collection valueCollection = dataCollection.values();
	    List<Map> collideList = new ArrayList<Map>(valueCollection);
	    List<Map> resultCollideList = new ArrayList();
	    for (int j = 0; j < collideList.size(); j++) {
		Map obj1 = (Map) collideList.get(j);
		Integer collideNum = (Integer) obj1.get("collideNum");
		if (collideNum > 1) {
		    resultCollideList.add(obj1);
		}
	    }

	    // 按照数量进行倒序
	    Collections.sort(resultCollideList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = ((Integer) obj2.get("collideNum")).compareTo((Integer) obj1.get("collideNum"));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    result.put("collideList", resultCollideList);

	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    private static Map addDataCollection(Map dataCollection, Map newData) {
	Map result = dataCollection;
	String newId = (String) newData.get("id");

	if (UtilValidate.isEmpty(dataCollection.get(newId))) {
	    Map oldData = new HashMap();
	    oldData.put("id", newId);
	    oldData.put("collideNum", 1);

	    result.put(newId, oldData);
	} else {
	    Map putData = new HashMap();
	    Map oldData = (Map) dataCollection.get(newId);
	    putData.putAll(oldData);
	    int collideNum = (int) oldData.get("collideNum") + 1;
	    putData.put("collideNum", collideNum);
	    result.put(newId, putData);
	}
	return result;

    }

    private static Map computerDataCollection(Map<String, Object> dataCollection, List<String> keywordList) {

	Map result = new HashMap();
	for (String key : dataCollection.keySet()) {

	    if ("".equals(key)) {
		continue;
	    }
	    if (key.length() < 2) {
		continue;
	    }
	    Map putData = new HashMap();
	    putData.put("id", key);
	    int collideNum = 0;
	    for (String keyword : keywordList) {
		if (keyword.contains(key)) {
		    collideNum = collideNum + 1;
		}
	    }
	    putData.put("collideNum", collideNum);
	    result.put(key, putData);
	}
	return result;

    }

    private static Map computerData(Delegator delegator, Map<String, Object> dataCollection,
	    List<GenericValue> customerList) throws GenericEntityException {

	Map result = new HashMap();
	for (String key : dataCollection.keySet()) {

	    if ("".equals(key)) {
		continue;
	    }
	    if (key.length() < 2) {
		continue;
	    }
	    List collideList = new ArrayList();
	    Map putData = new HashMap();
	    putData.put("id", key);
	    int collideNum = 0;
	    for (GenericValue customer : customerList) {
		String keyword = customer.getString("customerName");
		if (keyword.contains(key)) {
		    collideNum = collideNum + 1;

		    Map customerMap = new HashMap();
		    String ownerUserId = customer.getString("ownerUserId");
		    String ownerUserId_dictText = CrmServices.getPersonNameByUserLoginId(ownerUserId);
		    String bu_dictText = getBuNameByOwnerUserId(delegator, ownerUserId);

		    String customerName = customer.getString("customerName");
		    String customerId = customer.getString("id");
		    Timestamp createTime = customer.getTimestamp("createTime");
		    customerMap.put("ownerUserId_dictText", ownerUserId_dictText);
		    customerMap.put("ownerUserId_bu", bu_dictText);
		    customerMap.put("customerName", customerName);
		    customerMap.put("customerId", customerId);
		    customerMap.put("createTime", createTime);
		    collideList.add(customerMap);
//     	    		客户经理
//     	    		BU
//     	    		客户名称
//     	    		创建时间
		}
	    }

	    Collections.sort(collideList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = ((Timestamp) obj1.get("createTime")).compareTo((Timestamp) obj2.get("createTime"));
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	    putData.put("collideList", collideList);
	    putData.put("collideNum", collideNum);
	    result.put(key, putData);
	}
	return result;

    }

    private static String getBuNameByOwnerUserId(Delegator delegator, String ownerUserId)
	    throws GenericEntityException {
	List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship", UtilMisc.toMap("statusId",
		"PARTY_ENABLED", "partyRelationshipTypeId", "COMPANY_EMPLOYEE", "partyIdTo", ownerUserId), null, true);
	Debug.log("coRelationshipList ===" + coRelationshipList);

	if (UtilValidate.isEmpty(coRelationshipList)) {
	    return "";
	}
	GenericValue coRelationship = EntityUtil.getFirst(coRelationshipList);
	String buId = coRelationship.getString("partyIdFrom");

	List<GenericValue> dataDictionaryList = delegator.findByAnd("DataDictionary",
		UtilMisc.toMap("dictionaryCode", buId, "dictionaryTypeId", "BU_DEPARTMENT"), null, true);

	if (UtilValidate.isEmpty(dataDictionaryList)) {
	    return "";
	}
	Debug.log("dataDictionaryList ===" + dataDictionaryList);
	GenericValue dataDictionary = EntityUtil.getFirst(dataDictionaryList);
	String buName = dataDictionary.getString("description");

	return buName;
    }

}
